← Back to Angular, page 10

angular-0181 · Medium mid

How does the OAuth 2.0 / OIDC authorization code flow with PKCE work in a single page Angular app, and how do a route guard and an HTTP interceptor use it?

The app redirects the browser to the identity provider with a code challenge (the hash of a secret verifier). After login the provider redirects back with a code, and the app exchanges the code plus the verifier for tokens. A guard sends users without a token to login and remembers the return URL, and an interceptor adds the access token to API calls only.

Full answer

A single page app cannot keep a client secret, so it uses the authorization code flow with PKCE (Proof Key for Code Exchange). This is the recommended flow for browser apps. The older implicit flow, which returned tokens in the URL, is no longer recommended.

The steps:

  1. The app creates a random code_verifier and a state value, and stores them (session storage). It computes code_challenge = base64url(SHA-256(code_verifier)).
  2. It redirects the browser to the identity provider's /authorize URL with response_type=code, client_id, redirect_uri, scope=openid profile, state, code_challenge and code_challenge_method=S256.
  3. The user logs in at the provider (not in your app), and the provider redirects back to your redirect_uri with code and state.
  4. The app checks that state matches (protection against forged callbacks), then calls the /token endpoint with grant_type=authorization_code, the code and the original code_verifier. The provider hashes the verifier and compares it with the challenge from step 2. An attacker who steals the code cannot use it without the verifier.
  5. The response has an access token (to call APIs), an ID token (who the user is, OIDC), and often a refresh token. The app keeps the access token in memory when possible, and refreshes it before it expires.

In Angular:

  • Functional guard: canActivate checks auth.isAuthenticated(). If false, it saves the wanted URL and returns a UrlTree for /login. After login, navigate to the saved URL.
  • Interceptor: adds Authorization: Bearer <token> only for requests to your API origin, never to third party URLs. On a 401, it can refresh once and retry.
  • Callback route: reads code and state, calls the token exchange, then navigates on.

Security points: guards only improve the user experience, because the server must always check the token. Do not store tokens in localStorage if you can avoid it, since any XSS can read them. Check iss, aud and expiry on the server. In production, use a maintained library (angular-auth-oidc-client, oidc-client-ts, or a provider SDK) and not hand-written code. Another option is a backend for frontend (BFF) that keeps tokens in HTTP-only cookies.

typescript
import { HttpInterceptorFn } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export async function pkceChallenge(verifier: string): Promise<string> {
  const bytes = new TextEncoder().encode(verifier);
  const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
  return btoa(String.fromCharCode(...hash)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

export function randomString(length = 64): string {
  const bytes = crypto.getRandomValues(new Uint8Array(length));
  return Array.from(bytes, (b) => 'abcdefghijklmnopqrstuvwxyz0123456789-._~'[b % 40]).join('');
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  readonly token = signal<string | null>(null); // kept in memory
  returnUrl = '/';

  isAuthenticated(): boolean {
    return this.token() !== null;
  }

  async authorizeUrl(): Promise<string> {
    const verifier = randomString();
    const state = randomString(16);
    sessionStorage.setItem('pkce_verifier', verifier);
    sessionStorage.setItem('oauth_state', state);
    const params = new URLSearchParams({
      response_type: 'code',
      client_id: 'school-spa',
      redirect_uri: 'https://app.example.com/callback',
      scope: 'openid profile',
      state,
      code_challenge: await pkceChallenge(verifier),
      code_challenge_method: 'S256',
    });
    return `https://id.example.com/authorize?${params}`;
  }
}

export const authGuard: CanActivateFn = (_route, state) => {
  const auth = inject(AuthService);
  if (auth.isAuthenticated()) {
    return true;
  }
  auth.returnUrl = state.url; // remember where the user wanted to go
  return inject(Router).parseUrl('/login');
};

export const bearerInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  if (token && req.url.startsWith('https://api.example.com/')) {
    return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
  }
  return next(req);
};

Angular 20.3, type-checked. A Karma test checks the PKCE challenge against the example from RFC 7636, the guard redirect with the saved return URL, and that the interceptor adds the header only for the API origin. The redirect to a real identity provider and the token exchange were not run.

Key points

  • Use authorization code flow with PKCE for browser apps. The verifier never travels in the redirect.
  • Check `state` on return, then exchange `code` plus verifier for tokens.
  • Guard redirects with a return URL. Interceptor adds the token to your API only.
  • The server must validate tokens. Prefer a maintained library or a BFF.

Common mistakes

  • Adding the bearer token to every outgoing request, including third party ones.
  • Skipping the `state` check.
  • Treating the guard as security instead of user experience.

Follow-ups

  • Why is PKCE needed when there is no client secret?
  • Where would you keep the access token, and what are the risks?
  • How would you refresh a token without making several refresh calls at once?

Tips

  • Walk through the five steps in order.
  • Explain what PKCE protects against in one sentence.
  • Mention libraries and the BFF option.

Evaluation rubric

  • Explains the code flow with PKCE correctly.
  • Implements guard and interceptor safely.
  • Notes the security limits of client-side checks.