Understanding the OAuth authorization code flow with diagrams
Here is what this post covers:
- Introduction
- What OAuth is
- The authorization code flow
- Responding to attacks
- Wrapping up
- Next time
- References
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.
| Concept | Description |
|---|---|
| Authorization flow | The steps for granting an app* access. There are several, depending on the kind of app |
| Scope | The data and operations the app* can access. The app specifies it in the request |
| Access token | The 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
| Role | Description | In the photo print example |
|---|---|---|
| Resource owner | The owner of the data (the user) | You, who posted photos on Instagram |
| Client | The app that wants to access the user’s data | The photo print service (print.example.com) |
| Authorization server | Authenticates the user and issues access tokens | The server behind Instagram’s login and consent screen (auth.example.net) |
| Resource server | Holds 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 isauth.example.net, the resource server isapi.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.
Two kinds of clients
| Kind | Characteristics | Example |
|---|---|---|
| Confidential client | Can keep a secret (the client secret) safe and use it to prove its identity to the authorization server | Web app |
| Public client | The app itself is distributed to users' devices, so it cannot keep a secret and cannot use a client secret | Mobile 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.
| Flow | When it is used |
|---|---|
| Authorization code flow | The user logs in in the browser and allows the app to access their data |
| Client credentials flow | No user is involved; servers talk to each other |
| Device authorization grant | Logging 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.
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.
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
| Parameter | Meaning |
|---|---|
response_type | The authorization flow to use. code for the authorization code flow |
client_id | The identifier of the client |
redirect_uri | The URL the authorization server redirects to after the user allows access. Here it is the client's callback URL (https://print.example.com/callback) |
scope | The range of access being requested (here, reading photos) |
state | An unguessable value for CSRF protection (covered later) |
Step 2: Login and consent (arrows 4, 5)
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.
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.
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.
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.
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_urisent 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).
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.
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.
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
stateas is when it redirects - c: The client compares the returned value with the one in the session, and aborts if they do not match
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.
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.
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_uriexactly matches the registered URL - c: If it does not match, the server does not redirect and shows an error screen
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
stateprotects against CSRF, and an exact match onredirect_uriprotects 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.