JA

Understanding OAuth PKCE with diagrams

Here is what this post covers:

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.

Diagram of where the secret lives. A web app keeps the secret on the client's own server (the print service's server), hidden from users. A mobile app is distributed to the user's phone, so a secret embedded in it can be pulled out by analysis. Web app Mobile app BrowserOn the user's device Client's serverOn the print service's side client_secret Hidden from users The app itselfOn the user's phone client_secret Can be pulled out by analysis

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.

Sequence diagram of code interception without PKCE. A malicious app registers the same custom URL scheme as the legitimate app and receives the authorization code from the OS after the redirect. With no secret, the authorization server cannot tell the apps apart and hands over an access token. The red arrows are the attack steps. User (Phone browser) Legitimate app (Print app) com.example.print: Malicious app (Same phone) com.example.print: Auth server (Instagram) auth.example.net Registers the same scheme in advance 1 Open auth screen 2 Authorization request 3 Login and consent 4 Redirect (with code) 5 OS passes it to the malicious app 6 Ask for a token 7 Access token Can't tell it from the legitimate app

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.

Diagram of code_verifier and code_challenge. Hashing code_verifier with SHA-256 and encoding it with Base64URL gives code_challenge. code_verifier cannot be recovered from code_challenge. code_verifier (kept in the app)dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk Hash with SHA-256 Encode with Base64URL Cannot be reversed code_challenge (sent in the authorization request)E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

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

ParameterMeaning
code_verifierAn unguessable random string the app creates (43 to 128 characters). Sent in the token request
code_challengeThe code_verifier hashed with SHA-256 and turned into a string with Base64URL. Sent in the authorization request
code_challenge_methodHow 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.

Sequence diagram of the whole authorization code flow with PKCE. Steps 2, 4, 5, 10 and 11 in purple are the parts PKCE adds. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data

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.

Sequence diagram. Steps 1 and 2 in green are Step 1, creating the passphrase. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data

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.

Sequence diagram. Steps 3 to 5 in green are the authorization request of Step 2. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data
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.

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.

Sequence diagram. Steps 6 to 9 in green are the login, consent and code issuing of Step 3. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data
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.

Sequence diagram. Steps 10 to 12 in green are the token exchange of Step 4. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data
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).

Diagram of the authorization server check. It hashes the received code_verifier with SHA-256, encodes it with Base64URL, and compares the result with the stored code_challenge. If they match, it issues an access token. Received code_verifier (Step 4)dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk SHA-256 → Base64URL Calculated code_challengeE9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM Compare Stored code_challenge (Step 2)E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM If they match, issue an access token

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).

Sequence diagram. Steps 13 and 14 in green are the API access of Step 5. User (Phone browser) Client (Print app) com.example.print: Auth server (Instagram) auth.example.net Resource server (Instagram API) api.example.net 1 Tap "Choose photos" 2 Create verifier, calculate challenge 3 Open auth screen 4 Authorization request (with code_challenge) 5 Store code_challenge 6 Show login and consent screen 7 Log in and allow 8 Redirect (with code) 9 Pass code to the app 10 Code + verifier 11 Hash verifier and compare 12 Access token 13 API request with token 14 Photo data
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.

Sequence diagram of PKCE stopping code interception. a, the legitimate app creates code_verifier and calculates code_challenge. b, the authorization server stores code_challenge. Even if a malicious app intercepts the code and asks for a token, c, there is no matching code_verifier, so the authorization server rejects it. User (Phone browser) Legitimate app (Print app) com.example.print: Malicious app (Same phone) com.example.print: Auth server (Instagram) auth.example.net a Create verifier, calculate challenge 1 Open auth screen 2 Authorization request (with code_challenge) b Store code_challenge 3 Login and consent 4 Redirect (with code) 5 OS passes it to the malicious app 6 Ask for a token (no verifier) c No verifier or no match → reject 7 Return an error

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.

statePKCE
Who checksThe clientThe authorization server
What is comparedThe value saved in the session and the value returned in the redirectThe stored code_challenge and the hash of the received code_verifier
Main attack preventedCSRF (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_verifier is 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
  • state lets 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.

References