QA
Intermediate LevelAuthentication & Authorization

How do you implement OAuth 2.0 PKCE (Proof Key for Code Exchange) step-by-step?

❓ Interview Prompt: Explain code_verifier generation, code_challenge calculation (SHA256), public clients, and authorization code verification.

Proof Key for Code Exchange (PKCE) (RFC 7636) is mandatory for OAuth 2.0 public clients (Single Page Apps, Mobile Apps) that cannot securely hide a client secret.

Step-by-Step PKCE Implementation:

1
Generate Code Verifier: Client creates a high-entropy random string (43 to 128 chars from '[A-Z, a-z, 0-9, -, ., _, ~]').
2
Compute Code Challenge: Client calculates SHA-256 hash of 'code_verifier' and Base64URL-encodes the result:

$$\text{code\_challenge} = \text{Base64URL}(\text{SHA256}(\text{code\_verifier}))$$

3
Authorization Request: Client redirects browser to Auth Server including 'code_challenge' and 'code_challenge_method=S256'.
4
Token Exchange: When exchanging the authorization code, client sends the unhashed 'code_verifier'.
5
Server Verification: Auth Server hashes the received 'code_verifier' and verifies it matches the original 'code_challenge'.

Code Implementation Example

typescript
import crypto from 'crypto';

// 1. Generate PKCE Code Verifier & Code Challenge (Node.js/Browser)
function generatePkcePair() {
  const verifier = crypto.randomBytes(32).toString('base64url');
  const challenge = crypto
    .createHash('sha256')
    .update(verifier)
    .digest('base64url');

  return { verifier, challenge };
}
💡Generating PKCE code_verifier and SHA-256 code_challenge pair.
🎯 Interview Key Takeaway

PKCE generates a dynamic verifier and SHA-256 challenge per authorization attempt, securing public clients without secrets.

#PKCE#OAuth 2.0#SHA256#Security#Intermediate
Back to all Authentication & Authorization Questions→

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?