EasyAuthentication📖 Theory Question

What is OAuth 2.0 PKCE and when should you use it?

💡

Hint

PKCE replaces the client secret for public clients (SPAs, mobile apps) — proves the token recipient is the same app that started the flow

Full Answer

PKCE (Proof Key for Code Exchange, pronounced "pixie") is an OAuth 2.0 extension that protects the authorization code flow for public clients (SPAs, mobile apps) that can't securely store a client secret.

The problem with SPAs: A client secret embedded in a SPA's JavaScript bundle is public — anyone can extract it and impersonate your app.

How PKCE works:

  1. App generates a random code verifier (43–128 chars) and computes its SHA-256 hash → code challenge.
  2. Authorization request includes the code challenge.
  3. Auth server stores the code challenge alongside the issued authorization code.
  4. Token exchange request includes the original code verifier.
  5. Auth server hashes the verifier and compares to stored challenge — only the original app can match.
// Step 1: generate
const codeVerifier = generateRandomString(64);
const codeChallenge = base64urlEncode(sha256(codeVerifier));

// Step 2: redirect with challenge
window.location.href = `${authServer}/authorize?
  code_challenge=${codeChallenge}&code_challenge_method=S256&...`;

Use PKCE for: all SPAs, mobile apps, any public client. It's now recommended even for confidential clients.

More Authentication Questions

EasyWhat are the security differences between storing a JWT in localStorage vs an HttpOnly cookie?EasyWhat is refresh token rotation and why is it important?EasyWhat is the difference between authentication and authorization?EasyWhat is SSO (Single Sign-On) and how is it implemented on the frontend?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint