Course contents

12. Security and Identity Lesson 4 of 8

OAuth 2.0

The authorization code flow with PKCE step by step: redirects, consent, the back-channel code exchange, scopes, refresh tokens, and what OAuth 2.1 removed.

18 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • OAuth lets a user grant an app limited, revocable access to an API without giving the app their password.
  • Authorization code + PKCE: redirect with state and code_challenge, consent at the authorization server, one-time code back through the browser, tokens over the back channel with the code_verifier.
  • Scopes cap what the client may do on the user’s behalf; the API still enforces what the user may access.
  • Short-lived access tokens and rotating refresh tokens; with locally verified tokens the authorization server is off the API request path.
  • OAuth 2.1 removes the implicit and password grants and requires exact redirect URIs and PKCE; RFC 9700 is the current security best practice.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

OAuth 2.0 (RFC 6749) is a framework for delegated authorization: a user (the resource owner) lets an application (the client) access their data at an API (the resource server) with limited permissions, through tokens issued by an authorization server. The client never sees the user’s password, and the user can revoke the grant later.

OAuth 2.1 is the IETF’s consolidation of OAuth 2.0 with the extensions and security lessons learned since 2012: PKCE (RFC 7636), exact redirect URI matching, no implicit or password grants, and the practices in the OAuth 2.0 Security Best Current Practice (RFC 9700, published January 2025).

Why it exists

Before OAuth, an app that wanted your photos asked for your password at the photo service. It then had full access, forever, and the only way to revoke it was to change your password. OAuth replaces the password with a token that is scoped (only photos, only read), short-lived, tied to one app, and revocable from the user’s account settings.

How it works

Authorization code flow with PKCE, the flow for any client acting for a user:

  1. Prepare. The client generates a high-entropy code_verifier, derives code_challenge = BASE64URL(SHA-256(code_verifier)), and a state value bound to the user’s session.
  2. Authorization request (front channel). The client redirects the browser to the authorization endpoint with response_type=code, client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256. The server checks the redirect URI exactly against the registered ones.
  3. Authenticate and consent. The user logs in at the authorization server (passkey, password and MFA, SSO) and approves the requested scopes.
  4. Authorization response (front channel). The server redirects back to redirect_uri with a short-lived, single-use code and the state. The client checks state against the session. Servers may also return iss (RFC 9207) so a client that talks to several servers can detect mix-up attacks.
  5. Token request (back channel). The client posts grant_type=authorization_code, the code, the redirect URI and the code_verifier to the token endpoint, plus client authentication if it is confidential (private-key JWT or mTLS preferred over shared secrets). The server checks the verifier against the stored challenge and returns an access token, usually a refresh token, the granted scope and expires_in.
  6. API calls. The client sends Authorization: Bearer <token>. The resource server validates it (locally if it is a JWT access token per RFC 9068, otherwise via introspection, RFC 7662), checks audience and scope, and applies its own authorization for the user.
  7. Refresh. When the access token expires, the client uses grant_type=refresh_token. Public clients must have refresh tokens rotated or sender-constrained (RFC 9700).

Other grants. Client credentials for machine-to-machine calls with no user. Device authorization grant (RFC 8628) for TVs and CLIs: the device shows a code and the user approves on a phone. Token exchange (RFC 8693) for services that need a downscoped token for a downstream call.

Client types. Confidential clients (server-side apps) can keep a credential secret. Public clients (native and browser apps) cannot, which is why PKCE was invented for them; OAuth 2.1 makes PKCE required for public clients and RFC 9700 recommends it for confidential clients too.

Errors on the API. RFC 6750: 401 with WWW-Authenticate: Bearer error="invalid_token" for missing, expired or bad tokens; 403 with error="insufficient_scope" when the token lacks the scope.

When to use it

  • Third-party apps that access users’ data at your API (the original use case).
  • Your own apps (web, mobile, CLI) authenticating against a central identity provider, combined with OpenID Connect for login.
  • Service-to-service authorization with client credentials and short-lived tokens.

When not to

  • A single web app with its own users and no API consumers: a server-side session is simpler.
  • As a login protocol on its own: an access token says the client may call an API, not who the user is or that they just authenticated. Use OpenID Connect’s ID token for login.
  • Rolling your own authorization server for production: use a mature product or service and certified libraries.

Trade-offs

Choice You gain You pay
Authorization server separate from apps One place for login, MFA, consent and revocation Another critical service; redirects add round trips to login
JWT access tokens vs opaque Local validation, authorization server off the hot path Revocation waits for expiry
Short access tokens Faster revocation More refresh traffic
BFF (confidential client) vs browser public client Tokens never reach JavaScript; real client authentication A backend per frontend; cookie session and CSRF defences
Fine-grained scopes Least privilege per client Consent screens and scope management get complex

Alternatives

  • Server-side sessions when there is no delegation and only your own web app.
  • API keys for simple server-to-server access: easy, but long-lived, unscoped by user and hard to rotate.
  • Mutual TLS between services, often combined with OAuth (RFC 8705 binds tokens to the client certificate).
  • SAML in older enterprise SSO deployments; OpenID Connect is its common modern replacement.

Failure modes

  • Code interception or injection without PKCE.
  • Open redirectors and loose redirect URI matching (wildcards, prefix matching) leaking codes to attacker URLs.
  • Missing or unchecked state, letting an attacker log a victim into the attacker’s account.
  • Tokens in URLs (implicit grant, query parameters) leaking through logs, history and referrers.
  • Over-broad scopes or long-lived tokens turning a client compromise into a full account compromise.
  • Mix-up attacks in clients that use several authorization servers.
  • Using OAuth for login without OpenID Connect, accepting any access token as proof of identity.
  • Authorization server outage: no new logins, and failures spread as access tokens expire.

In production

Use authorization code + PKCE everywhere users are involved, and client credentials for machines. Register exact redirect URIs. Keep access tokens short and audience-restricted, rotate refresh tokens, and revoke grants when users disconnect apps. For browser apps, prefer a backend-for-frontend so tokens stay server-side. Consider sender-constrained tokens (DPoP, RFC 9449, or mTLS) for high-value APIs. Monitor the authorization server like the critical dependency it is, and choose access-token lifetimes knowing they set how long an outage is invisible and how long revocation takes.

Common misconceptions

  • “OAuth is an authentication protocol.” It is delegated authorization. OpenID Connect adds authentication.
  • “PKCE is only for mobile apps.” It began there; current guidance applies it to all clients.
  • “Scopes are permissions on data.” They limit the client. A token with photos:read still must not read someone else’s photos.
  • “The access token is for the client to read.” To the client it is opaque; only the resource server should interpret it. Use the ID token for user information.

Interview angle

Expect to draw the authorization code flow with PKCE, labelling front channel (redirects carrying the challenge, code and state) and back channel (code and verifier for tokens). Explain what PKCE and state each stop, why implicit and password grants are gone, how scopes and audiences limit tokens, refresh token rotation, and what happens when the authorization server is down. Bonus points for BFF, DPoP and the difference between OAuth and OpenID Connect.

Model assumptions

The flow is a scripted illustration, not a simulation: redirects, consent, the code exchange, PKCE checks, refresh and the implicit-grant leak are hand-placed packets with illustrative one-way durations (8 ms browser to client, 14 ms browser to authorization server, 6 ms client to authorization server, 5 ms client to API). The engine has no model of browsers, redirects or cryptography. The outage step is simulated: the client app sends Poisson-distributed API calls at 200 per second to a resource server with 32 workers and 3 ms mean service time (lognormal, cv 0.3), which validates JWT access tokens locally, so the authorization server is not on the path; its failure is modelled as the node going offline. Token expiry during the outage is described, not simulated. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Four roles and a delegation

    Alice uses a printing app that wants to read photos from her account at a photo service. She should not give the app her password. OAuth 2.0 (RFC 6749) lets her grant the app limited, revocable access instead.

    The roles: the resource owner (Alice), the client (the printing app), the authorization server (issues tokens after asking Alice) and the resource server (the photo API, which accepts tokens). OAuth is about *delegated authorization*; logging in with it is OpenID Connect, a layer on top. Alice clicks “Connect photos”. All flow steps in this lesson are a scripted illustration.

    Scene: Four parties: Alice’s browser, the client app, the authorization server and the resource server. Alice clicks a button in the client app to connect her photos.

    Key idea: OAuth lets a user grant an app scoped access to an API without sharing credentials with the app.

  2. 2. Step 1: send the user to the authorization server

    The app creates two secrets for this attempt: a random code_verifier, and a random state tied to Alice’s session. It derives the code_challenge = BASE64URL(SHA-256(code_verifier)) and redirects the browser:

    GET /authorize?response_type=code&client_id=print-app&redirect_uri=https://print.example/cb&scope=photos:read&state=…&code_challenge=…&code_challenge_method=S256

    Only the challenge travels through the browser; the verifier stays with the app. The authorization server checks that redirect_uri exactly matches one registered for print-app.

    Scene: The client app answers with a redirect; the browser follows it to the authorization server’s authorize endpoint carrying the client id, redirect URI, scope, state and PKCE code challenge.

    Key idea: The authorization request carries client_id, exact redirect_uri, scope, state and a PKCE code_challenge (S256).

  3. 3. Step 2: the user logs in and consents

    The authorization server shows its own login page (the app never sees Alice’s password), then a consent screen: *Print App wants to view your photos*. Alice approves.

    The server redirects the browser back to the registered redirect_uri with a short-lived, single-use authorization code and the same state. The app checks that state matches the one it stored for Alice’s session; otherwise an attacker could inject their own code into her session (login CSRF). This is the front channel: everything here passes through the browser, so nothing here is a token.

    Scene: The authorization server shows a login and consent page, Alice approves, and the browser is redirected back to the client app with an authorization code and the state value.

    Key idea: The front channel returns only a one-time code plus state; the user authenticates at the authorization server, never at the client.

  4. 4. Step 3: exchange the code on the back channel

    The app’s backend calls the token endpoint directly, not through the browser: POST /token with grant_type=authorization_code, the code, the same redirect_uri, the code_verifier, and its client authentication (a confidential client uses a private-key JWT, mTLS or a secret; a public client such as a mobile app has none).

    The server hashes the verifier and compares it with the challenge it saw in step 1, checks the code is unused and unexpired, and returns an access token (short-lived, often a JWT), a refresh token, the granted scope, and expires_in.

    Scene: The client app’s backend sends the code and the PKCE code verifier to the token endpoint and receives an access token and a refresh token.

    Key idea: Tokens come over the back channel only, after the server checks SHA-256(code_verifier) against the earlier code_challenge.

  5. 5. Step 4: call the API with the access token, within its scopes

    The app calls GET /photos with Authorization: Bearer <access token>. The resource server verifies the token (locally for a JWT, or by introspection), checks the audience, and checks the scope: photos:read is enough, so it answers.

    Then the app tries DELETE /photos/7. The token is valid, but it does not carry photos:write, so the API answers 403 with error="insufficient_scope". Scopes cap what the app may do on Alice’s behalf; the API still checks what Alice herself may touch.

    Scene: The client app calls the resource server with its access token and gets photos back. A second call that needs a write scope the token lacks is rejected with 403 insufficient_scope.

    Key idea: Scopes limit the client, not the user. Missing scope = 403 insufficient_scope; bad or expired token = 401.

  6. 6. Why PKCE: a stolen code is useless

    Codes travel through the browser, and they leak: a malicious app on the phone registered for the same custom URL scheme, a proxy log, a browser history sync. Here a malicious app intercepts Alice’s code and races to the token endpoint with it.

    It does not have the code_verifier, which never left the real client. The server cannot match the challenge and answers invalid_grant. This is why OAuth 2.1 requires PKCE for public clients and the security BCP (RFC 9700) recommends it for all clients: it also stops an attacker injecting a stolen code into a confidential client.

    Scene: The authorization server redirects with a code, which a malicious app intercepts and sends to the token endpoint. Without the code verifier the authorization server rejects it.

    Key idea: PKCE binds the code to the client instance that started the flow: no verifier, no token.

  7. 7. Access tokens expire; refresh tokens renew them

    Ten minutes later the access token has expired and the API answers 401. The app sends its refresh token to the token endpoint (grant_type=refresh_token), with its client authentication, and receives a new access token and, with rotation, a new refresh token; the old one stops working. Alice is not involved.

    Refreshing is also where revocation bites: if Alice disconnects the app in her account settings, the next refresh fails. The app may ask for fewer scopes on refresh, never more.

    Scene: The client app’s call fails with 401 because the access token expired; it exchanges its refresh token at the authorization server for new tokens and retries successfully.

    Key idea: Short-lived access tokens plus rotating refresh tokens: renew silently, revoke at the authorization server.

  8. 8. The authorization server is not on the request path

    Now the simulation runs: the app makes 200 API calls per second with its access token, and the resource server verifies each JWT locally. One second in, the authorization server goes down.

    API calls carry on with no errors: nothing on their path needs the authorization server. What does break: new users cannot connect the app, and each existing grant fails at its next refresh, so the outage becomes visible as access tokens expire. The access-token lifetime is how long the system rides out an authorization server outage, and also how long a revoked grant keeps working.

    Scene: The client app sends 200 requests per second to the resource server. After one second the authorization server goes offline; API calls keep succeeding because tokens are verified locally.

    Key idea: With self-contained access tokens, an authorization server outage stops logins and refreshes, not API calls (until tokens expire).

  9. 9. What OAuth 2.1 removed, and why

    The implicit grant returned the access token directly in the redirect URL fragment, with no code exchange. Tokens in URLs leak through browser history, logs and referrers, and nothing binds them to the client. Here the token lands in the browser and leaks to a malicious app.

    The resource owner password grant had the app collect Alice’s password itself, which is exactly what OAuth was meant to avoid. OAuth 2.1 drops both; the security BCP (RFC 9700) says not to use them. Also required now: exact redirect URI matching, PKCE, and no bearer tokens in query strings. Devices without browsers use the device authorization grant (RFC 8628); machine-to-machine calls use client credentials.

    Scene: An old implicit-grant flow: the authorization server returns the access token directly in the redirect URL, and from there it leaks to a malicious app. OAuth 2.1 removes this grant and the password grant.

    Key idea: Implicit and password grants are gone: use authorization code + PKCE for users, client credentials for machines.

  10. 10. Code, verifier, token, scope

    The app makes 200 API calls per second again, with the authorization server back up for logins and refreshes.

    The flow to remember: redirect with state and a PKCE code_challenge; user logs in and consents at the authorization server; a one-time code comes back through the browser; the app redeems it on the back channel with the code_verifier; the API accepts short-lived access tokens within their scopes; refresh tokens rotate. Use a library or a certified identity provider for the protocol details, and for browser apps keep the tokens in a backend (BFF).

    Scene: The client app sends 200 requests per second to the resource server with its access token; the authorization server is online for logins and refreshes. Nothing fails.

    Key idea: Authorization code + PKCE, exact redirect URIs, state, narrow scopes, short access tokens, rotating refresh tokens.