CodePark/ questions / OAuth 2.0 & OpenID Connect
START PRACTICINGPRACTICE
Backend question · Auth & security › OAuth 2.0 & OpenID Connect

Walk through the Authorization Code flow with PKCE. What does PKCE protect against?

PKCE (Proof Key for Code Exchange) stops an attacker from using a stolen or injected authorization code. Here is the flow, step by step.

1. Start. The client creates a random secret called the code_verifier. From it, the client makes code_challenge = BASE64URL(SHA256(code_verifier)). The client then redirects the user to the authorization endpoint with:

  • response_type=code
  • client_id
  • redirect_uri
  • scope
  • state
  • the code_challenge
  • code_challenge_method=S256

2. Login. The user logs in and gives consent. The authorization server redirects back to the registered redirect_uri. It sends a short-lived, single-use code and the same state.

3. Exchange. The client checks that state matches. Then it posts the code and the original code_verifier to the token endpoint. A confidential client (a server app that can keep a secret) also authenticates itself here.

4. Check. The server hashes the verifier and compares it with the stored challenge. Only if they match does it issue tokens.

Why it works: the verifier never passed through the browser. So a stolen or injected code is useless without it. OAuth 2.1 and the Security BCP (Best Current Practice) recommend PKCE for every client type.

  • The client creates a random code_verifier and sends an S256 code_challenge in the redirect.
  • The code comes back to an exact registered redirect_uri, together with state.
  • The client exchanges the code at the token endpoint and sends the verifier.
  • The server checks that the verifier matches the challenge.
  • PKCE stops intercepted or injected authorization codes.