How-To Guide

How to Implement the OAuth 2.0 Authorization Code Flow

Add the authorization code flow to a server-rendered app with state, PKCE, exact redirect URIs and server-side token storage.

On this page

  1. Introduction
  2. When to Use this Flow
  3. The Redirect and the State Parameter
  4. Exchanging the Code on the Server
  5. Storing Tokens Securely
  6. Validating the Resulting Token
  7. Logout and Revocation
  8. Common Pitfalls and Conclusion

Introduction

The authorization code flow is the foundation of OAuth 2.0 for apps that have a backend. The user is redirected to the authorization server, authenticates there, and is redirected back with a short-lived code; the backend exchanges that code for tokens, which never touch the browser. Compared with the implicit flow it is safer, because tokens stay server-side and the browser only ever sees an opaque code. This tutorial builds the flow for a server-rendered app, including the checks that stop the common attacks: state, PKCE, exact redirect URI matching and secure token storage.

When to Use this Flow

Use the authorization code flow whenever a confidential client can keep a secret and the user interacts with a browser: a server-rendered web app, a backend-for-frontend, a mobile app with a backend, a desktop app with a loopback redirect. The defining property is that the token exchange happens on a server you control, so tokens are stored where the browser cannot read them.

Do not use the implicit flow, which returns tokens directly in the redirect fragment and is deprecated in OAuth 2.1. For a public client that cannot keep a secret, use the same code flow plus PKCE, which replaces the static secret with a per-request proof. The code flow with the right extensions covers every case.

The Redirect and the State Parameter

The flow starts when the app redirects the browser to the authorization endpoint with response_type=code, client_id, redirect_uri, scope and state. The user authenticates at the provider, which redirects back to the registered redirect_uri with a code and the state. The state is an unguessable value the app generated and stored in the user’s session; on return, the app verifies it.

State prevents cross-site request forgery against the callback: without it, an attacker could trick a victim’s browser into completing a flow the attacker started, binding the victim’s account to the attacker’s data. Generate state from a cryptographically random source, store it server-side with the user’s session, and verify it once, invalidating it after use.

import { randomBytes, createHash } from 'node:crypto';

export function startLogin(session: Session, provider: Provider): string {
  const state = randomBytes(16).toString('base64url');
  const verifier = randomBytes(32).toString('base64url');
  const challenge = createHash('sha256').update(verifier).digest('base64url');

  session.oauthState = state;         // stored server-side, per user
  session.codeVerifier = verifier;    // needed at exchange time

  const url = new URL(provider.authorizationEndpoint);
  url.searchParams.set('response_type', 'code');
  url.searchParams.set('client_id', provider.clientId);
  url.searchParams.set('redirect_uri', provider.redirectUri);
  url.searchParams.set('scope', 'openid profile email');
  url.searchParams.set('state', state);
  url.searchParams.set('code_challenge', challenge);
  url.searchParams.set('code_challenge_method', 'S256');
  return url.toString();
}

Exchanging the Code on the Server

On the callback, the server verifies state, then posts the code to the token endpoint along with the client credentials, the code_verifier and the exact redirect_uri used in the request. The client secret is sent from the server, never from the browser, which is what makes the client confidential. The provider validates everything and returns tokens in the response body.

The redirect_uri in the exchange must match the one in the authorization request byte for byte and must be registered exactly with the provider. If the provider allows wildcard matching, an attacker can redirect the code to a host they control; an exactly registered redirect URI is what closes that hole. Never derive the redirect URI from user input such as a next parameter.

export async function handleCallback(req: Request, session: Session, provider: Provider) {
  const { code, state } = readParams(req);
  if (!state || state !== session.oauthState) throw new Error('state_mismatch');
  session.oauthState = undefined;   // single-use

  const res = await fetch(provider.tokenEndpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: provider.redirectUri,
      client_id: provider.clientId,
      client_secret: provider.clientSecret,   // server-side only
      code_verifier: session.codeVerifier ?? '',
    }),
  });
  if (!res.ok) throw new Error('token_exchange_failed: ' + res.status);
  return res.json(); // { access_token, refresh_token?, id_token?, expires_in }
}

Storing Tokens Securely

Store tokens server-side against the user’s session, in an encrypted store or in memory, and keep the session cookie HttpOnly, Secure and SameSite. The browser should never hold the access or refresh token, because any script on the page could read it. A session cookie identifies the server-side session, and the token stays behind the server boundary.

Refresh tokens are the highest-value secret: they are long-lived and can mint new access tokens. Protect them with the same care and prefer rotation, where each refresh issues a new refresh token and invalidates the old one. If a rotated-away token is presented, the provider detects theft and revokes the family of tokens.

res.cookie('sid', sessionId, {
  httpOnly: true,      // unreadable by page scripts
  secure: true,        // HTTPS only
  sameSite: 'lax',     // blocks most cross-site sends
  path: '/',
});
// tokens live in the server-side session store keyed by sid,
// never in localStorage or a readable cookie

Validating the Resulting Token

If you requested an OpenID Connect id_token, verify its signature against the provider’s JWKS, and check iss, aud, exp and the nonce you sent. The nonce binds the id_token to this authentication attempt, defeating replay of a captured token. If you only requested an access token for calling the provider’s API, you do not need to validate it, but you must not treat it as authentication of the user.

For your own APIs, verify the access token’s signature, issuer and audience before trusting it, so a token minted for another client or environment is rejected. Do not accept a token just because it is signed; audience confusion is a real attack where a token from one service is replayed against another.

Logout and Revocation

Logging out should clear the server-side session and, where the provider supports it, revoke the refresh token so it cannot be replayed. Local logout alone leaves a valid refresh token that a stolen copy could use indefinitely. Call the provider’s revocation endpoint with the refresh token on logout, and treat a failed revocation as a reason to log it, not to keep the token.

Also expire access tokens on schedule and refresh proactively before expiry rather than reactively after a 401, to avoid a thundering herd of refreshes when many sessions expire at once. Spread the refresh across the token’s lifetime.

Common Pitfalls and Conclusion

Do not skip state, or the callback is CSRF-able. Do not use a predictable state. Do not derive the redirect URI from input. Do not send the client secret to the browser. Do not store tokens in localStorage. Do not accept an id_token without verifying the nonce. And never use the implicit flow for a new app, because the token ends up where the browser can read it.

The authorization code flow keeps tokens on the server, uses a one-time code in the browser, and is protected by state, PKCE and exact redirect matching. Exchange the code server-side with the client secret, store tokens where the browser cannot read them, validate the resulting token’s signature and claims, and revoke on logout. Done this way, OAuth authentication is the least risky part of your application.

Sources: RFC 6749: OAuth 2.0, OpenID Connect Core, OAuth 2.0 Security Best Current Practice.

FAQ

Why not just accept the token from the front end?
Because the browser is not a safe place for tokens: any script, including an injected one, can read them from memory or storage. Keeping the exchange and the tokens server-side behind an HttpOnly session cookie removes that exposure.
Do I still need state if I use PKCE?
Yes. PKCE protects the token exchange from code interception; state protects the callback from CSRF. They defend against different attacks and are both required.

Related Examples