Web Security 10 🛡️ OAuth 2.0 & OpenID Connect — Implementing Authorization Code Flow with PKCE, state validation, and BFF patterns
OAuth 2.0 is the industry-standard protocol for authorization, while OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0. Together, they allow applications to verify a user’s identity and obtain limited access to user accounts on an HTTP service, such as Google, GitHub, or an internal identity provider. Instead of sharing credentials directly with a third-party application, OAuth allows a user to grant a “token” that represents their permission. This delegative architecture is the foundation of modern “Login with…” buttons and cross-service integrations.
However, the protocol has evolved significantly to address security vulnerabilities found in early implementations. The “Implicit Flow,” which once passed tokens directly in the URL fragment, is now deprecated due to the risk of token leakage. The modern standard for both mobile and web applications is the Authorization Code Flow with Proof Key for Code Exchange (PKCE). Furthermore, for Single Page Applications (SPAs), the industry has shifted toward the Backend For Frontend (BFF) pattern, moving token management out of the browser entirely to protect against Cross-Site Scripting (XSS).
This chapter covers the end-to-end implementation of the Authorization Code Flow with PKCE, the role of OIDC in identity verification, and the architectural shifts required to keep tokens secure in modern web environments. We will analyze how to generate and validate state parameters, implement the PKCE handshake, and structure a BFF to act as a secure proxy for authentication.
Key point: Modern OAuth 2.0 implementations must abandon the Implicit Flow in favor of the Authorization Code Flow with PKCE, while SPAs should utilize a Backend For Frontend (BFF) to ensure that sensitive access tokens are never stored in the browser’s vulnerable JavaScript environment.
Why X exists
1. The credential sharing problem.
Before OAuth, if a third-party app wanted to access your data on another service, you had to give that app your actual username and password. This was a massive security risk, as the app could do anything you could do, and you had no way to revoke access without changing your password. OAuth exists to provide “delegated access,” where the app gets a limited-scope token instead of your credentials.
2. The scope limitation problem.
OAuth allows for “scopes,” which define exactly what an application can do. For example, an app might request a read:profile scope but not a delete:account scope. This principle of least privilege ensures that even if an application is compromised, the damage is limited to the permissions explicitly granted by the user.
3. The token leakage problem (Implicit Flow).
Early SPAs used the Implicit Flow, where the Access Token was returned directly in the URL hash. This made tokens visible in browser history, server logs, and Referer headers. PKCE (Proof Key for Code Exchange) was created to secure the Authorization Code Flow for “public clients” (apps that cannot keep a secret), ensuring that only the application that initiated the login can exchange the code for a token.
4. The Identity vs. Authorization gap.
OAuth 2.0 was designed for authorization—giving an app permission to do something. It didn’t provide a standard way to find out who the user is. OpenID Connect (OIDC) was created to add an identity layer, providing a standardized “ID Token” in JWT format that contains user profile information like name and email.
5. The XSS/LocalStorage vulnerability.
In modern web security, storing tokens in localStorage is considered a high risk because any XSS vulnerability allows an attacker to steal the tokens. The BFF (Backend For Frontend) pattern exists to move the OAuth dance and token storage to a secure server-side environment, using HttpOnly cookies to maintain the session with the browser.
6. The CSRF in Auth problem.
Without verification, an attacker could trick a user’s browser into completing an OAuth flow initiated by the attacker, potentially linking the user’s account to the attacker’s credentials. The state parameter exists to ensure that the authentication response coming back to the app is a response to a request that the app actually started.
a. Authorization Code Flow with PKCE
The Authorization Code Flow with PKCE is the most secure way to implement OAuth 2.0. It involves a two-step process: first, obtaining an authorization code, and second, exchanging that code for tokens. PKCE adds a cryptographic bridge between these two steps to prevent “Authorization Code Injection” attacks.
// 1. Generate PKCE Verifier and Challenge
const codeVerifier = generateRandomString(64);
const codeChallenge = base64UrlEncode(sha256(codeVerifier));
// 2. Generate State to prevent CSRF
const state = generateRandomString(32);
sessionStorage.setItem('auth_state', state);
sessionStorage.setItem('code_verifier', codeVerifier);
// 3. Redirect User to Authorization Server
const authUrl = `https://auth.provider.com/authorize?` +
`response_type=code&` +
`client_id=${CLIENT_ID}&` +
`redirect_uri=${REDIRECT_URI}&` +
`scope=openid profile email&` +
`state=${state}&` +
`code_challenge=${codeChallenge}&` +
`code_challenge_method=S256`;
window.location.href = authUrl;
In this first stage, the client generates a secret code_verifier and a derived code_challenge. The server stores the challenge. When the user returns with a code, the client sends the original code_verifier. The server hashes this verifier and compares it to the stored challenge; if they match, it proves the same client is making both requests.
The exchange step happens on the backend (or via a secure POST request) once the user is redirected back to the application with the code.
// 4. Handle Redirect and Exchange Code
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const returnedState = params.get('state');
if (returnedState !== sessionStorage.getItem('auth_state')) {
throw new Error("CSRF Attack Detected!");
}
const tokenResponse = await fetch('https://auth.provider.com/token', {
method: 'POST',
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
code_verifier: sessionStorage.getItem('code_verifier')
})
});
The server validates the code and the verifier, then issues the Access Token and ID Token. By requiring the code_verifier, the server ensures that even if an attacker intercepted the code in the URL, they couldn’t use it because they lack the original secret verifier.
b. OpenID Connect (OIDC) and the ID Token
OpenID Connect extends OAuth 2.0 by introducing the ID Token. While the Access Token is an opaque string or JWT meant for the API (the Resource Server), the ID Token is a JWT meant for the client application to read user details.
// A decoded OIDC ID Token example
{
"iss": "https://auth.provider.com",
"sub": "user_12345",
"aud": "my_client_id",
"exp": 1672531200,
"iat": 1672527600,
"name": "Jane Doe",
"email": "jane@example.com",
"nonce": "secure_random_nonce"
}
The iss (issuer) and aud (audience) claims are critical for security. The client must verify that the iss matches the expected provider and the aud matches its own client_id. This prevents an ID Token issued for “App A” from being used to log into “App B.”
OIDC also defines a UserInfo endpoint. If the ID Token doesn’t contain all the required data, the client can use the Access Token to fetch additional profile details.
async function getUserInfo(accessToken: string) {
const response = await fetch('https://auth.provider.com/userinfo', {
headers: { Authorization: `Bearer ${accessToken}` }
});
return response.json(); // Returns { name, email, picture, etc. }
}
The integration of OIDC allows developers to treat the identity provider as a single source of truth for user data, simplifying user management and enabling Single Sign-On (SSO) across multiple internal and external applications.
c. The BFF (Backend For Frontend) Pattern
For Single Page Applications, the BFF pattern is the modern security recommendation from the OAuth working group. In a BFF architecture, the SPA does not handle OAuth tokens directly. Instead, a dedicated server-side component (the BFF) performs the OAuth flow and stores the tokens in a server-side session.
// The BFF handles the callback and stores tokens in a secure session
app.get('/api/auth/callback', async (req, res) => {
const { code, state } = req.query;
// ... Validate state, perform code exchange ...
const tokens = await exchangeCodeForTokens(code);
// Store tokens in a server-side session (e.g., Redis)
req.session.tokens = tokens;
// Set an encrypted, HttpOnly, SameSite cookie
res.cookie('auth_session', sessionID, {
httpOnly: true,
secure: true,
sameSite: 'strict'
});
res.redirect('/dashboard');
});
When the SPA needs to call an API, it sends a request to the BFF. The BFF retrieves the Access Token from the session and proxies the request to the actual Resource Server, adding the Authorization: Bearer <token> header on the server side.
// The BFF proxies the request
app.get('/api/proxy/data', async (req, res) => {
const accessToken = req.session.tokens.access_token;
const apiResponse = await fetch('https://api.external.com/data', {
headers: { Authorization: `Bearer ${accessToken}` }
});
const data = await apiResponse.json();
res.json(data);
});
This pattern completely eliminates the need to store tokens in localStorage. Since the authentication is handled via HttpOnly cookies, JavaScript cannot access the session identifier, and since the tokens are on the server, they are never exposed to the browser at all, neutralizing the threat of token theft via XSS.
Complete Example Session
// ============================================
// PART 1: PKCE GENERATION
// ============================================
const verifier = generateVerifier(); // Secure random string
const challenge = sha256AndBase64(verifier);
// ============================================
// PART 2: THE AUTH URL (Initiating Login)
// ============================================
const state = generateState();
const loginUrl = buildUrl('https://idp.com/auth', {
client_id: 'app_123',
response_type: 'code',
code_challenge: challenge,
code_challenge_method: 'S256',
state: state,
scope: 'openid profile offline_access' // OIDC + Refresh Token
});
// ============================================
// PART 3: CALLBACK HANDLING (State Check)
// ============================================
const { code, state: returnedState } = getQueryParams();
if (returnedState !== savedState) throw Error("State mismatch!");
// ============================================
// PART 4: CODE EXCHANGE (PKCE)
// ============================================
const tokens = await post('https://idp.com/token', {
grant_type: 'authorization_code',
code,
code_verifier: verifier, // Prove we started the request
client_id: 'app_123'
});
// ============================================
// PART 5: ID TOKEN VALIDATION (OIDC)
// ============================================
const idToken = decodeJwt(tokens.id_token);
if (idToken.iss !== 'https://idp.com') throw Error("Invalid Issuer");
if (idToken.aud !== 'app_123') throw Error("Invalid Audience");
// ============================================
// PART 6: SESSION CREATION (BFF)
// ============================================
req.session.accessToken = tokens.access_token;
req.session.refreshToken = tokens.refresh_token;
// ============================================
// PART 7: REFRESHING TOKENS
// ============================================
const newTokens = await post('https://idp.com/token', {
grant_type: 'refresh_token',
refresh_token: req.session.refreshToken,
client_id: 'app_123'
});
// ============================================
// PART 8: API PROXYING
// ============================================
// Browser calls /api/data -> BFF adds token -> API
const headers = { 'Authorization': `Bearer ${req.session.accessToken}` };
const data = await fetch('https://api.com/user/data', { headers });
// ============================================
// PART 9: SCOPE VALIDATION (Resource Server)
// ============================================
// The API verifies the token has the 'profile' scope
if (!token.scopes.includes('profile')) return res.status(403);
// ============================================
// PART 10: LOGOUT (RP-Initiated Logout)
// ============================================
req.session.destroy();
const logoutUrl = `https://idp.com/logout?id_token_hint=${tokens.id_token}`;
res.redirect(logoutUrl);
This session demonstrates the lifecycle of an OIDC session from PKCE initialization to secure API proxying and finally logout, following the BFF architectural pattern.
Quick Reference
OAuth 2.0 Roles
| Role | Description |
|---|---|
| Resource Owner | The User (who owns the data) |
| Client | Your Application (requesting access) |
| Authorization Server | The Identity Provider (Login page) |
| Resource Server | The API (holding the data) |
Grant Types Comparison
| Grant Type | Status | Use Case |
|---|---|---|
| Auth Code + PKCE | Standard | SPAs, Mobile, Web Apps |
| Client Credentials | Standard | Machine-to-Machine (No User) |
| Implicit | Deprecated | Legacy SPAs (Do not use) |
| Password | Deprecated | Trusted first-party apps (Do not use) |
PKCE Components
| Term | Generated By | Purpose |
|---|---|---|
| Code Verifier | Client | High-entropy random secret |
| Code Challenge | Client | SHA256 Hash of the Verifier |
| Challenge Method | Client | Usually ‘S256’ |
Best Practices
✅ Do This:
// Use Authorization Code Flow with PKCE always // ✅
// Use OIDC for authentication (Identity) // ✅
// Implement state validation to prevent CSRF // ✅
// Use BFF pattern for SPAs to avoid token exposure // ✅
// Validate ID Token signatures and claims // ✅
// Request minimal scopes for the required action // ✅
❌ Don’t Do This:
// Don't use the Implicit Flow // ❌
// Don't store tokens in LocalStorage or SessionStorage // ❌
// Don't share your Client Secret in browser code // ❌
// Don't skip state or nonce validation // ❌
// Don't use OAuth 2.0 (Access Tokens) for Auth // ❌
// Don't accept tokens without verifying 'iss' and 'aud'// ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Token Theft (XSS) | Tokens stored in LocalStorage | Move tokens to BFF / HttpOnly Cookies |
| State Mismatch | State not stored or checked | Generate unique state, verify on return |
| CSRF in Callback | Missing state parameter | Always use state or OIDC nonce |
| Audience Confusion | ID Token aud not checked | Verify aud === my_client_id |
| Code Injection | PKCE not implemented | Use code_challenge / code_verifier |
| Token Leakage | Tokens passed in URL fragments | Use Auth Code Flow (POST exchange) |
Real-World Examples
1. PKCE Code Verifier
const verifier = binToHex(crypto.getRandomValues(new Uint8Array(32)));
2. Auth URL Construction
const url = new URL("https://auth.com/authorize");
url.searchParams.set("code_challenge", challenge);
3. State Generation
const state = crypto.randomUUID();
localStorage.setItem('auth_state', state);
4. OIDC Nonce
// Prevents replay attacks for ID Tokens
url.searchParams.set("nonce", randomNonce);
5. BFF Proxy Header
proxyReq.setHeader('Authorization', `Bearer ${session.token}`);
6. Scopes Request
scope: "openid profile email offline_access"
7. Client Secret (Backend Only)
// NEVER in the browser
const secret = process.env.OAUTH_CLIENT_SECRET;
8. Redirect URI Match
// Must be exact match in IDP config
redirect_uri: "https://app.com/callback"
9. JWT Signature Check
const isValid = jwt.verify(token, jwksKey, { algorithms: ['RS256'] });
10. Refresh Token Usage
grant_type: "refresh_token"
Visual
Auth Code Flow + PKCE
┌──────────┐ ┌──────────────┐ ┌─────────────┐
│ CLIENT │ │ AUTH SERVER │ │ USER │
└────┬─────┘ └──────┬───────┘ └──────┬──────┘
│ 1. Generate PKCE │ │
│ 2. Redirect + Challenge │
├───────────────────────┼────────────────────────►│
│ │ 3. Login & Consent │
│ │◄────────────────────────┤
│ 4. Code + State │ │
│◄──────────────────────┤ │
│ 5. Code + Verifier │ │
├──────────────────────►│ │
│ │ 6. Validate PKCE │
│ 7. Tokens (JWT) │ │
│◄──────────────────────┤ │
└────┴─────┘ └──────┴───────┘ └──────┴──────┘
The BFF Pattern
┌─────────────┐ ┌───────────────┐ ┌─────────────┐
│ BROWSER │ │ BFF │ │ API │
│ (SPA) │ │ (Server) │ │ (Resource) │
└──────┬──────┘ └──────┬────────┘ └──────┬──────┘
│ 1. Auth Req │ │
├─────────────────────►│ │
│ │──► OAuth Flow with IDP │
│ 2. Session Cookie │ │
│◄─────────────────────┤ │
│ │ │
│ 3. API Call │ │
├─────────────────────►│ 4. Add Access Token │
│ ├───────────────────────►│
│ 5. JSON Response │ │
│◄─────────────────────┤◄───────────────────────┤
└──────┴──────┘ └───────────────┘ └─────────────┘
Token Security Hierarchy
┌─────────────────────────────────────────────────────────────┐
│ TOKEN STORAGE SECURITY │
│ │
│ [BEST] BFF Architecture: Tokens never touch browser. │
│ [GOOD] HttpOnly Cookies: Tokens in browser, but no JS access.│
│ [POOR] Memory Storage: Tokens lost on refresh, but safe-ish.│
│ [DANGEROUS] LocalStorage: Vulnerable to 100% of XSS attacks.│
└─────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Protocol | OAuth 2.0 (Authorization) |
| Identity Layer | OpenID Connect (OIDC) |
| Standard Flow | Auth Code Flow + PKCE |
| Identity Format | JWT (ID Token) |
| CSRF Defense | state parameter / OIDC nonce |
| Code Hijack Defense | PKCE (code_challenge) |
| SPA Pattern | Backend For Frontend (BFF) |
Key takeaways:
- OAuth is for access, OIDC is for identity. Use OIDC when you need to know who the user is, and OAuth Access Tokens when you need to call APIs on their behalf.
- The Implicit Flow is dead. Modern browsers and security standards require the Authorization Code Flow with PKCE for all client types, including SPAs.
- PKCE protects public clients. By using a temporary cryptographic secret (
code_verifier), PKCE ensures that an intercepted authorization code cannot be used by an attacker. - State validation is mandatory. Always generate a unique
statefor every login attempt and verify it upon the user’s return to prevent Cross-Site Request Forgery. - Protect your tokens. Avoid
localStorage. Use the BFF pattern to keep tokens on the server, using secureHttpOnlycookies to maintain the user’s session with the frontend. - Verify JWTs correctly. When receiving an ID Token, check the signature, issuer (
iss), and audience (aud) to ensure the token is valid and intended for your application.
Remember: OAuth 2.0 and OIDC are powerful but complex. Security vulnerabilities often arise from using outdated flows or storing tokens incorrectly. By adopting the Authorization Code Flow with PKCE and the BFF pattern, you align your application with modern security best practices and protect your users from token theft and account hijacking.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!