Authentication interview question · Most asked
Explain the OAuth 2.0 Authorization Code flow with PKCE.
Summary
The client redirects the user to the authorization server with a code challenge; after login and consent, the server redirects back with a one-time authorization code, which the client exchanges (with the original code verifier) for tokens at the token endpoint. PKCE prevents intercepted codes from being redeemed by attackers.
Longer Answer
Steps: (1) client creates a random code_verifier and its SHA-256 code_challenge, plus state (CSRF) and nonce (OIDC replay protection); (2) redirect to /authorize; (3) user authenticates; (4) redirect back with code and state; (5) client verifies state and POSTs code + verifier to /token; (6) receives access token (+ ID token, refresh token). PKCE is required for public clients (SPAs, mobile) and recommended for all clients in OAuth 2.1. The implicit flow is deprecated.
Code Example
// PKCE values in the browser
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = base64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
location.href = `${AUTH_URL}/authorize?response_type=code&client_id=${CLIENT_ID}` +
`&redirect_uri=${encodeURIComponent(REDIRECT)}&scope=openid%20profile%20email` +
`&code_challenge=${challenge}&code_challenge_method=S256&state=${state}&nonce=${nonce}`;
Key Points
- Code + PKCE for all clients
- state prevents CSRF
- nonce prevents ID token replay
- Implicit flow is deprecated
- Exchange code server-side when possible
More most-asked Authentication questions
- What is the difference between authentication and authorization?
- Compare session-based authentication with token-based (JWT) authentication.
- What are the most common JWT security pitfalls?
- What are OAuth 2.0 and OpenID Connect, and how do they differ?
- How do refresh tokens work, and how do you secure them?
- How should passwords be stored?
- What is multi-factor authentication, and which factors are strongest?
- How do you secure session cookies?