JA

Understanding the OAuth authorization code flow with diagrams

Here is what this post covers:

Introduction

From late September to early October, so many data breaches were in the news that a line from the “Prince of Vegetables” came to mind: “Is this a clearance sale of leaked data?”

I have always thought security matters, and I read about how OAuth works in Qiita and Zenn articles and in a book. I felt like I understood it. But when I imagine explaining it to teammates or clients in a design job, or to a friend in the same field as a way of getting it out of my head, I can picture myself getting stuck partway. The roles of the players, and who exchanges what with whom in what order, still have not stuck.

A familiar example: when you try to connect Instagram or X to another app, a screen asks “Allow this app to access your account?” OAuth is what runs behind that screen.

I have more authentication and authorization design work these days, so I’ll use this chance to sort out the basics of OAuth and the “authorization code flow”, using an everyday social media example and sequence diagrams.

What OAuth is

OAuth (Open Authorization) is a protocol for delegating access rights. It lets users allow another application to access their data without handing over their password.

An example

Say you want to delegate your rights to a photo print service so it can print photos you posted on Instagram.

The easiest way is to hand your ID and password to the print service as is (delegating them) and let it log in to Instagram for you. But then the print service, now holding your ID and password, can do anything with your Instagram account (it could post on your behalf, read your DMs, or even change your password).

If you let a third party (the print service) access your account, that access should meet two conditions:

  • It is limited to specific data and operations (for example, read-only access to photos)
  • It is valid only for a limited time

In OAuth, the roles introduced below achieve this using three concepts.

ConceptDescription
Authorization flowThe steps for granting an app* access. There are several, depending on the kind of app
ScopeThe data and operations the app* can access. The app specifies it in the request
Access tokenThe key for accessing data on another service. It expires, and its power is limited to the scope

*The app is the side being granted access (the print service in this example). The data it accesses lives on Instagram.

The roles

RoleDescriptionIn the photo print example
Resource ownerThe owner of the data (the user)You, who posted photos on Instagram
ClientThe app that wants to access the user’s dataThe photo print service (print.example.com)
Authorization serverAuthenticates the user and issues access tokensThe server behind Instagram’s login and consent screen (auth.example.net)
Resource serverHolds the user’s data and controls access to it (the API)The API that returns Instagram photo data (api.example.net)

This post uses the following domains:

  • The print service: print.example.com
  • Instagram’s side: example.net (the authorization server is auth.example.net, the resource server is api.example.net)

Both are made up for explanation and are not Instagram’s real domains. In the figures, the authorization server is shortened to “Auth server”.

Here are the four roles as a diagram. The numbers show the order of the exchanges.

Diagram of the four roles. The resource owner (you) uses the client (a photo print service, print.example.com) (1) and logs in and allows access at the authorization server (auth.example.net) (2). The authorization server issues an access token to the client (3), and the client fetches photos from the resource server (api.example.net) with the token (4). Instagram (example.net) Resource ownerYou ClientPhoto print serviceprint.example.com Auth serverLogin and consent screenauth.example.net Resource serverPhoto data APIapi.example.net 1 Uses 2 Log in and allow 3 Issues token 4 Fetch photos with the token

Two kinds of clients

KindCharacteristicsExample
Confidential clientCan keep a secret (the client secret) safe and use it to prove its identity to the authorization serverWeb app
Public clientThe app itself is distributed to users' devices, so it cannot keep a secret and cannot use a client secretMobile app

A web app’s code runs on the client’s own server (the print service’s server), so the secret can sit where users cannot see it. A mobile app is downloaded and run on each user’s device, so even a secret embedded in it can be pulled out by anyone who analyzes the app.

Kinds of authorization flows

OAuth has several authorization flows, depending on the kind of app and the situation. These are the main ones.

FlowWhen it is used
Authorization code flowThe user logs in in the browser and allows the app to access their data
Client credentials flowNo user is involved; servers talk to each other
Device authorization grantLogging in on devices where typing is awkward, such as TVs and game consoles

Of these, the authorization code flow is the one commonly used by web apps. The photo print example is one of those. From here on, we’ll look at the authorization code flow in detail.

The authorization code flow

Overview

The authorization code flow exchanges an “authorization code” received from the authorization server for an access token.

  • It uses browser redirects to send the user to the authorization server and then back to the client
  • It uses the client secret to exchange the code for a token, so it is meant for web apps (confidential clients) that can keep a secret

The whole flow

Here is the whole flow first. The boxes at the top also show each player’s domain. In the steps after this, the arrows for that step are shown in green.

Sequence diagram of the whole authorization code flow. Arrows 1 to 11 show the user, client, authorization server and resource server exchanging messages. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data

Step 1: Authorization request (arrows 1-3)

When the user clicks “Choose photos from Instagram”, the client builds an authorization URL and redirects the user to the authorization server.

Sequence diagram. The green arrows 1 to 3 are the authorization request of Step 1. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data

After this redirect, the browser sends the following HTTP request to the authorization server (auth.example.net). Line breaks are added for readability.

GET /authorize?response_type=code
  &client_id=s6BhdRkqt3
  &redirect_uri=https%3A%2F%2Fprint.example.com%2Fcallback
  &scope=photos.read
  &state=35ce HTTP/1.1
Host: auth.example.net
ParameterMeaning
response_typeThe authorization flow to use. code for the authorization code flow
client_idThe identifier of the client
redirect_uriThe URL the authorization server redirects to after the user allows access. Here it is the client's callback URL (https://print.example.com/callback)
scopeThe range of access being requested (here, reading photos)
stateAn unguessable value for CSRF protection (covered later)

The user logs in at the authorization server (Instagram) and agrees to let the client access their photos. The “Allow this app to access your account?” screen from the introduction is this consent screen. The only party that receives the password is the authorization server, and the client never sees it.

Sequence diagram. The green arrows 4 and 5 are the login and consent of Step 2. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data

Step 3: Issuing the authorization code (arrows 6, 7)

After consent, the authorization server redirects the user to the redirect_uri (= the client, print.example.com). The authorization code is embedded in the URL and reaches the client through the browser.

Sequence diagram. The green arrows 6 and 7 are the issuing of the authorization code in Step 3. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data

What the authorization server returns to the browser is the following HTTP response.

HTTP/1.1 302 Found
Location: https://print.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=35ce

302 Found on the first line is the status code, which means “please go to a different URL”. The URL to go to is in the Location header on the second line. This mechanism is called an HTTP redirect.

When the browser receives a 302, it automatically requests the URL in Location. The authorization server does not send the code to the client directly. It tells the browser “go to this URL”. In the diagram, arrow 6 is the 302 response and arrow 7 is the browser requesting the new URL. Arrows 2 and 3 (Step 1) work the same way.

HTTP redirect diagram. The authorization server returns 302 Found with a Location header to the browser, and the browser automatically requests that URL, delivering the authorization code to the client. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net 6 302 Found (Location: https://print.example.com/callback?code=…) Browser requests the Location URL automatically 7 GET /callback?code=…

The authorization server links the authorization code it issued (code=SplxlOBeZQQYbYS6WxSbIA) to the client_id that was in the authorization request (s6BhdRkqt3).

Step 4: Exchanging the code for an access token (arrows 8, 9)

The client sends the authorization code it took from the URL to the authorization server, together with its client ID and client secret, and receives an access token. This exchange does not go through the browser. It is a server-to-server call.

Sequence diagram. The green arrows 8 and 9 are the token exchange of Step 4. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data
POST /token HTTP/1.1
Host: auth.example.net
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fprint.example.com%2Fcallback

The value of the Authorization header is client_id:client_secret, Base64-encoded. Presenting the secret proves that the request comes from the legitimate client.

{
  "access_token": "2YotnFZFEjr1zCsicMWpAA",
  "token_type": "Bearer",
  "expires_in": 3600
}

Three points to keep in mind:

  • The client secret is highly confidential and must never be exposed
  • The best practice is to make an authorization code single-use
  • The redirect_uri sent in the exchange must be the same value as in the authorization request

Step 5: Accessing the API (arrows 10, 11)

The client attaches the access token to its request and gets the photo data from the resource server (api.example.net).

Sequence diagram. The green arrows 10 and 11 are the API access of Step 5. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Click "Choose photos" 2 Redirect to auth screen 3 Authorization request 4 Show login and consent screen 5 Log in and allow 6 Redirect to redirect_uri (with code) 7 Deliver the code 8 Code + ID + secret 9 Access token 10 API request with token 11 Photo data
GET /photos HTTP/1.1
Host: api.example.net
Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA

Why the authorization code comes in between

The authorization code flow has two paths for data: one that goes through the browser, and one where the servers talk to each other directly.

Diagram of the two data paths. The authorization code travels from the authorization server through the browser to the client and appears in the URL, so it can be intercepted on the way. The access token is passed directly between the client and the authorization server without going through the browser. User's browserURLs stay in history and logs Auth serverauth.example.net Clientprint.example.com Auth code (in the URL) Auth code (in the URL) Can be intercepted Code + secret Access token Server to server, directly (not via the browser)

Only the authorization code appears in the URL during the browser redirect. The access token is passed only on the server-to-server path. URLs tend to stay in browser history and logs, and they can be intercepted on the way and seen by a third party. An authorization code cannot access the API by itself, and exchanging it for a token requires the client secret. So even if a code leaks, it cannot be abused right away.

Responding to attacks

Even if you build exactly what the flow describes, there are attacks that abuse browser redirects. Here are two typical ones and how to stop them, with diagrams.

CSRF protection

Suppose the print service can also save edited photos back to the connected Instagram account. If state is not used, an attacker can get the victim’s photos in the following way. The red arrows are the attack steps.

Sequence diagram of a CSRF attack when state is not used. The attacker gets an authorization code for their own account and makes the victim open a trap link carrying it. The attacker's Instagram gets linked to the victim's account, and photos the victim saves go to the attacker's account. The red arrows are the attack steps. Attacker Victim (Browser) Client (Print service) print.example.com Instagram (Auth server + API) *.example.net 1 Log in and allow with own account 2 Attacker's authorization code Holds it back, does not send it to the client 3 Send trap link 4 Deliver attacker's code 5 Exchange code for token 6 Attacker's token Attacker's Instagram gets linked to the victim's account 7 Save photo to Instagram 8 Save victim's photo Saved to the attacker's account

The attacker gets an authorization code with their own Instagram account and holds it back without sending it to the client (1, 2). Then the attacker makes the victim open a callback URL carrying this code (https://print.example.com/callback?code=attacker's code) as a trap link (3, 4).

The client has no way to tell whether the code that arrived came from the victim’s own action or was planted by the attacker. It exchanges the code for a token as is, and links the attacker’s Instagram account to the victim’s print service account (5, 6). When the victim then saves a photo, it goes to the attacker’s account (7, 8).

An attack that uses a trap link to make someone send a request they did not intend is called CSRF (cross-site request forgery).

This is where the state parameter comes in. Its main role is to let the client check that the code coming back belongs to an authorization request that it started in the same browser. It does that in these steps:

  • a: The client creates an unguessable random value, saves it in the session, and adds it to the authorization request
  • b: The authorization server returns the same state as is when it redirects
  • c: The client compares the returned value with the one in the session, and aborts if they do not match
Sequence diagram of the state flow. a, the client creates state, saves it in the session and adds it to the authorization request. b, the authorization server returns the same state in the redirect. c, the client compares it with the session value. User (Browser) Client (Print service) print.example.com Auth server (Instagram) auth.example.net a Create state=35ce, save it in the session Redirect (state=35ce) Authorization request (state=35ce) Login and consent b Redirect (code=…&state=35ce) Deliver code and state c Matches the session value → continue

Even if the attacker uses a trap link, the state in that link is the value the attacker got in their own browser. It does not match the value saved in the victim’s session, so the check in c stops it.

Sequence diagram of state stopping the CSRF attack. The attacker sends a trap link and the victim delivers the attacker's code and state to the client, but check c finds they do not match the victim's session value, so the client aborts. Attacker Victim (Browser) Client (Print service) print.example.com 3 Send trap link 4 Deliver attacker's code and state c Doesn't match the session value → abort

Open redirect protection

If the authorization server does not restrict the values allowed for redirect_uri, an attacker can build a trap link whose redirect_uri points to the attacker’s own server (evil.example.org).

https://auth.example.net/authorize?response_type=code
  &client_id=s6BhdRkqt3
  &redirect_uri=https%3A%2F%2Fevil.example.org%2Fcallback

If the victim opens this link, the attacker gets the authorization code in the following way.

Sequence diagram of an open redirect attack. The attacker sends a trap link whose redirect_uri is the attacker URL, and the victim browser sends the authorization request. Because the victim is logged in, the authorization server redirects straight to the attacker URL and the authorization code reaches the attacker. The red arrows are the attack steps. Attacker (Attacker's server) evil.example.org Victim (Browser) Auth server (Instagram) auth.example.net 1 Send trap link 2 Authorization request (redirect_uri = attacker URL) Already logged in, so it issues a code right away 3 Redirect to attacker URL (with code) 4 Authorization code arrives

If the victim is already logged in to Instagram and has allowed this client before, neither the login screen nor the consent screen appears (2, 3). The authorization server redirects straight to the redirect_uri, and the authorization code reaches the attacker’s server (4). An authorization code is a voucher that can be exchanged for an access token, so losing it is dangerous.

Steps 2 and 3 are exactly the same exchange as in the normal authorization code flow. Only the contents of redirect_uri differ, so this cannot be stopped unless the authorization server checks it.

So the authorization server compares redirect_uri with the registered value using an exact match. Its role is to limit where authorization codes can be sent to the URLs the client registered. It checks in these steps:

  • a: The client registers its own callback URL (https://print.example.com/callback) with the authorization server in advance
  • b: When an authorization request arrives, the authorization server checks whether redirect_uri exactly matches the registered URL
  • c: If it does not match, the server does not redirect and shows an error screen
Sequence diagram of an exact match on redirect_uri stopping the open redirect attack. a, the client registers its callback URL in advance. b, the authorization server compares redirect_uri with the registered URL. c, it does not match, so the server shows an error screen instead of redirecting. Attacker (Attacker's server) evil.example.org Victim (Browser) Auth server (Instagram) auth.example.net Client (Print service) print.example.com a Register callback URL Later, the attacker sets a trap 1 Send trap link 2 redirect_uri = attacker URL b Exact match with registered URL? → No c Show error screen No redirect (no code issued)

Because c does not redirect, the authorization code never reaches the attacker. With a prefix or partial match, a URL such as https://print.example.com.evil.example.org/callback could slip through, so the comparison has to be an exact match.

Wrapping up

  • OAuth delegates access rights without handing over a password, limited in “scope” and in “time”
  • The authorization code flow has two stages, “authorization code → access token”, so the token never appears in a URL
  • state protects against CSRF, and an exact match on redirect_uri protects against open redirect

Next time

The authorization code flow in this post assumed a web app (a confidential client) that can keep the client secret safe. So what should a mobile app (a public client) do, since it cannot hold a secret?

The answer is a mechanism called PKCE (Proof Key for Code Exchange). In OAuth 2.1, the newer version of OAuth, public clients use this flow combined with PKCE. I covered PKCE with diagrams in the next post.

References