Application security

Implement OAuth 2.0 PKCE safely

Proof Key for Code Exchange (PKCE) binds an authorization code to the client that initiated a flow. This guide covers the browser and server responsibilities, the threat model and the checks that prevent common implementation errors.

Choose the right OAuth flow

Public browser and mobile clients cannot safely keep a client secret. Use Authorization Code with PKCE, register exact redirect URIs and avoid the deprecated implicit flow. Confidential server-side clients should still use PKCE where supported.

  • Identify whether the client is public or confidential
  • Register exact redirect URIs
  • Use Authorization Code with PKCE

Create and validate flow values

Generate a high-entropy code verifier, derive the S256 challenge, and bind a cryptographically random state value to the initiating browser session. Validate state on callback and exchange the code with the original verifier.

  • Generate an unpredictable verifier and state
  • Send only the derived challenge in the authorization request
  • Reject callbacks with missing or mismatched state

Store tokens according to the threat model

Avoid persistent browser storage for long-lived bearer tokens when a backend-for-frontend is feasible. If a browser client must hold tokens, minimize lifetime and scope, protect against XSS, and plan refresh-token rotation and revocation.

  • Use least-privilege scopes and short-lived access tokens
  • Keep secrets out of source code and browser bundles
  • Document revocation and session-expiry behavior

Test negative and replay cases

A successful login is not enough. Test state mismatch, code reuse, verifier mismatch, redirect URI mismatch, expired authorization codes and cross-account callback behavior before production rollout.

  • Add automated callback validation tests
  • Verify authorization codes cannot be reused
  • Review provider logs without recording tokens

Questions to keep in view

Does PKCE replace OAuth state?

No. PKCE protects authorization-code redemption; state remains an important request and callback correlation and CSRF defense. Use and validate both according to the provider's guidance.

Can a browser application use a client secret?

No. A browser bundle is public to its users. Treat it as a public client and use PKCE rather than attempting to conceal a secret in JavaScript.