Understanding OAuth PKCE with diagrams
Here is what this post covers:
- Introduction
- What goes wrong with mobile apps
- How PKCE works
- The authorization code flow with PKCE
- Why an intercepted code is useless
- How it differs from state
- Using PKCE in web apps
- Wrapping up
- Next time
- References
Introduction
In the previous post, I walked through the OAuth authorization code flow with the example of a photo print service importing photos from Instagram. That post assumed a web app (a confidential client) that can keep the client secret safe.
Things change when the same photo print service releases a mobile app. A mobile app cannot keep a secret safe, so with the previous flow as is, nothing stops an attacker who intercepts the authorization code.
The answer is PKCE (Proof Key for Code Exchange, pronounced “pixie”). This post sorts out what goes wrong with mobile apps and how PKCE prevents it, using the same example and sequence diagrams as last time. It also covers how PKCE differs from state from the previous post, and why web apps use it too.
What goes wrong with mobile apps
The secret cannot be hidden
In the previous flow, when the client exchanged the authorization code for an access token, it sent the client secret to prove that the request came from the legitimate client. A web app can keep the secret on the client’s own server (the print service’s server). It is not stored on the authorization server (Instagram). It sits on a server the client’s operator manages, so users cannot see it.
A mobile app is different. The app itself is downloaded to and runs on the user’s phone, so even a secret embedded in it can be pulled out by analyzing the app. In the terms of the previous post, it is a public client.
Without a secret, the authorization server has no way to check that whoever asks for a token is really the legitimate app. Anyone holding an authorization code can exchange it for a token.
Intercepting the authorization code
Mobile apps sometimes use an app-specific URL such as com.example.print:/callback (a custom URL scheme) as the redirect target (redirect_uri). When the browser opens this URL, the OS launches the app that registered the scheme and passes the URL to it.
The catch is that another app can register the same scheme. If a malicious app is installed on the same phone, it can intercept the authorization code in the following way and go on to get an access token. The red arrows are the attack steps.
Which app, the legitimate one or the malicious one, receives the authorization code from the redirect is up to the OS (4, 5). The malicious app uses the code it received to ask for a token right away (6). Because no secret is used, the authorization server cannot tell it apart from the legitimate app and hands over an access token (7).
An attack in which a malicious app intercepts the authorization code like this is called an authorization code interception attack. PKCE was designed to prevent it.
How PKCE works
A single-use passphrase
The idea of PKCE is to create a single-use passphrase on the spot for every authorization request. Unlike a secret embedded in the app ahead of time, it is created each time and thrown away after use, so analyzing the app does not reveal it.
The passphrase is a pair: code_verifier and code_challenge. code_verifier is a random string the app creates and keeps to itself. code_challenge is the code_verifier hashed with SHA-256 and turned into a string with Base64URL. The app sends only code_challenge to the authorization server first, and sends code_verifier for the first time when it exchanges the code for a token.
Hashing is a one-way calculation, so code_verifier cannot be derived from code_challenge. The code_challenge appears in a URL that passes through the browser and might be seen, but seeing it does not reveal the code_verifier.
Parameters
| Parameter | Meaning |
|---|---|
code_verifier | An unguessable random string the app creates (43 to 128 characters). Sent in the token request |
code_challenge | The code_verifier hashed with SHA-256 and turned into a string with Base64URL. Sent in the authorization request |
code_challenge_method | How the code_challenge was made. Set it to S256 (SHA-256). Sent in the authorization request |
code_challenge_method also has a plain option, which sends the value without hashing. With plain, though, anyone who sees the code_challenge also knows the code_verifier. The PKCE specification (RFC 7636) says that clients capable of using S256 must use S256.
The authorization code flow with PKCE
The whole flow
Here is the previous flow with the parts PKCE adds shown in purple. The domains are the same as last time, and the mobile app uses com.example.print:/callback as its redirect target.
Compared with last time, only three things change: the app first creates the passphrase (2), it adds code_challenge to the authorization request (4, 5), and when exchanging the code for a token it sends code_verifier instead of a secret, which the authorization server checks (10, 11). In the steps after this, the arrows for each step are shown in green.
Step 1: Creating the passphrase (arrows 1, 2)
When the user taps “Choose photos”, the app first creates a code_verifier and calculates the code_challenge from it.
Written in Python to show the idea, it looks like this:
import base64
import hashlib
import secrets
# An unguessable random string (43 characters)
code_verifier = secrets.token_urlsafe(32)
# Hash it with SHA-256 and turn it into a string with Base64URL (drop the trailing =)
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
This post uses the example values from the appendix of the PKCE specification (RFC 7636). The code_verifier is dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk, and the code_challenge calculated from it is E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM. The app stores the code_verifier inside itself and does not send it anywhere yet.
Step 2: Authorization request (arrows 3-5)
The app opens the authorization screen in the browser. At this point, it adds code_challenge and code_challenge_method to the authorization request.
GET /authorize?response_type=code
&client_id=s6BhdRkqt3
&redirect_uri=com.example.print%3A%2Fcallback
&scope=photos.read
&state=35ce
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256 HTTP/1.1
Host: auth.example.net
The authorization server stores the code_challenge it received (5). It links it to the authorization code it is about to issue, so it can check against it at the token request.
Note that mobile apps are required to open the authorization screen in the OS browser or an in-app browser tab, not in a WebView embedded in the app (RFC 8252). With a WebView, the app could read the password typed into the login screen.
Step 3: Login, consent and issuing the code (arrows 6-9)
This part is the same as last time. When the user logs in and allows access, the authorization server redirects to the redirect_uri, and the OS passes the authorization code to the app.
HTTP/1.1 302 Found
Location: com.example.print:/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=35ce
Step 4: Exchanging the code for a token (arrows 10-12)
The app sends the authorization code together with the code_verifier it stored when it created the passphrase. Since it has no secret, it does not send an Authorization header and puts client_id in the body instead.
POST /token HTTP/1.1
Host: auth.example.net
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=com.example.print%3A%2Fcallback
&client_id=s6BhdRkqt3
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
The authorization server hashes the received code_verifier the same way and compares it with the code_challenge it stored at the authorization request (11). If they match, it knows the request comes from the same app that sent the authorization request, so it issues an access token (12).
Step 5: Accessing the API (arrows 13, 14)
This is also the same as last time. The app attaches the access token to its request and gets photo data from the resource server (api.example.net).
GET /photos HTTP/1.1
Host: api.example.net
Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA
Why an intercepted code is useless
With PKCE, even if a malicious app intercepts the authorization code, it cannot exchange it for a token. Red marks the attack steps and purple marks the checks PKCE adds. a to c correspond to creating the passphrase, storing the code_challenge, and checking the code_verifier.
All the malicious app can get is the authorization code delivered by the redirect (4, 5). The code_verifier exists only inside the legitimate app and has not been sent anywhere yet. The code_challenge appears in a URL and might be seen, but the code_verifier cannot be derived from it. So the malicious app’s token request is rejected by the check in c.
The token request in which the legitimate app sends the code_verifier goes straight from the app to the authorization server over HTTPS, and does not pass through the browser or the OS’s routing. So the code_verifier cannot be intercepted on the way either.
How it differs from state
PKCE and state from the previous post both check that the party that started a request is the same one that comes back. But they differ in who checks and in the main attack they prevent.
state | PKCE | |
|---|---|---|
| Who checks | The client | The authorization server |
| What is compared | The value saved in the session and the value returned in the redirect | The stored code_challenge and the hash of the received code_verifier |
| Main attack prevented | CSRF (making the victim use the attacker's code) | Code interception (the attacker using the victim's code) |
The best current practice for OAuth security (RFC 9700) also says that a client that has confirmed the authorization server supports PKCE may rely on PKCE for CSRF protection as well.
Using PKCE in web apps
PKCE is not only for mobile apps. The same best current practice (RFC 9700) requires PKCE for public clients and recommends it for confidential clients such as web apps too. Even with a secret, it helps prevent authorization codes from being intercepted or an attacker’s code from being injected.
In OAuth 2.1, the newer version of OAuth, using PKCE with the authorization code flow is also the default. When you actually build the web app flow from the previous post, it is safer to combine it with PKCE.
Wrapping up
- A mobile app cannot keep a secret, so if its authorization code is intercepted, the code can be exchanged for a token as is
- PKCE creates a single-use passphrase (
code_verifier) for every authorization request and sends its hash (code_challenge) ahead of time - The
code_verifieris sent when exchanging the code for a token, and the authorization server compares the hashes, so a party that does not know the passphrase cannot get a token statelets the client prevent CSRF, and PKCE lets the authorization server prevent code interception
Next time
OAuth and PKCE, as covered so far, both decide what the print service may do. So what if the same print service adds “Log in with Instagram” and needs to know who logged in?
That is where OpenID Connect (OIDC), which sits on top of OAuth, comes in. I covered OIDC with diagrams in the next post.