OAuth 2.1 and OpenID Connect (OIDC): A Comprehensive Guide
As Sherlock, I'll deduce and explain OAuth 2.1 and OIDC with precision. OAuth 2.1 (draft as of 2024, consolidating RFC 6749/6750/6819/8707/6819/etc.) is an authorization framework for delegating access without sharing credentials. It mandates best practices like PKCE everywhere and deprecates insecure flows (e.g., Implicit, Resource Owner Password Credentials). OIDC 1.0 builds on OAuth 2.0/2.1 for authentication, adding ID Tokens (JWTs) with user claims.
Key roles:
- Client: App requesting access (e.g., SPA, mobile).
- Authorization Server (AS): Issues tokens (e.g., Auth0, Okta).
- Resource Server (RS): Protects APIs (often same as AS).
- Resource Owner (RO): User.
We'll cover flows, tokens, scopes/claims, PKCE, refresh, browser security, logout, best practices—with sequence diagrams (Mermaid) and code snippets (JS/Node.js focus for browser relevance).
1. Core Flows
OAuth 2.1 supports these flows (Implicit & ROPC deprecated):
| Flow | Use Case | Interactive? | PKCE Required? | Tokens |
|---|
| Authorization Code + PKCE | SPAs, mobile, browsers (recommended) | Yes | Yes | Access Token (AT), Refresh Token (RT), ID Token |
| Authorization Code | Confidential clients (servers) | Yes | No (but recommended) | AT, RT, ID Token |
| Client Credentials | M2M (no user) | No | N/A | AT |
| Device Authorization | IoT/TV | Yes (polling) | Yes | AT, RT |
Primary Flow: Authorization Code Flow with PKCE (Browser/SPA)
sequenceDiagram
participant Client as SPA Client
participant AS as Auth Server
participant RS as Resource Server
participant User as Browser User
Client->>Client: Generate code_verifier & code_challenge
Client->>AS: GET /auth?response_type=code&client_id=xyz&redirect_uri=cb&scope=openid profile&code_challenge=...&state=abc
AS->>User: Login Prompt
User->>AS: Authenticate & Consent
AS->>Client: 302 Redirect to cb?code=AUTH_CODE&state=abc
Client->>AS: POST /token (code, code_verifier, client_id, redirect_uri)
AS->>Client: {access_token, id_token, refresh_token, expires_in}
Client->>RS: GET /api/user (Authorization: Bearer AT)
RS->>Client: User Data
JS Client Snippet (Vanilla JS SPA):
// Step 1: Initiate auth (generate PKCE)
const verifier = generateCodeVerifier(); // e.g., crypto.randomUUID().replace(/-/g, '').slice(0, 43)
const challenge = await generateCodeChallenge(verifier); // SHA256(verifier) base64url
const authUrl = `https://as.example.com/auth?` +
`response_type=code&client_id=spa-client&redirect_uri=https://spa.example.com/cb&` +
`scope=openid profile email&code_challenge=${challenge}&code_challenge_method=S256&state=${crypto.randomUUID()}`;
window.location.href = authUrl;
// Callback handler
window.addEventListener('load', async () => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
const tokenRes = await fetch('https://as.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: 'spa-client',
code,
redirect_uri: 'https://spa.example.com/cb',
code_verifier: verifier // Stored in sessionStorage/memory
})
});
const tokens = await tokenRes.json();
localStorage.setItem('tokens', JSON.stringify(tokens)); // Secure storage (HttpOnly cookie better)
}
});
function generateCodeVerifier() {
return crypto.getRandomValues(new Uint8Array(32)).reduce((s, i) => s + String.fromCharCode(i % 96 + 32), '');
}
function generateCodeChallenge(verifier) {
return crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
.then(h => btoa(String.fromCharCode(...new Uint8Array(h)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''));
}
2. Tokens
- Access Token (AT): Bearer (opaque/JWT), short-lived (e.g., 1h). Sent to RS:
Authorization: Bearer <AT>.
- Refresh Token (RT): Long-lived, rotates on use (OAuth 2.1 best practice). Used to get new AT.
- ID Token (OIDC): JWT with user claims (e.g.,
sub, name). Signed/encrypted. Never send to RS.
JWT ID Token Example (decoded):
{
"iss": "https://as.example.com",
"sub": "user123",
"aud": "spa-client",
"exp": 1735689600,
"iat": 1735686000,
"nonce": "xyz", // Anti-CSRF
"claims": { "name": "Alice", "email": "alice@example.com" }
}
3. Scopes & Claims
- Scopes (OAuth): Permissions (strings, space-delimited). E.g.,
openid profile email → grants access to /userinfo.
openid: Triggers OIDC (ID Token).
- Claims (OIDC): User attributes in ID Token or
/userinfo endpoint.
| Scope | Claims |
|---|
openid | sub, iss, aud |
profile | name, family_name, picture |
email | email, email_verified |
Request: scope=openid profile. Fetch claims: GET /userinfo with AT.
Node.js RS Validation:
const jwt = require('jsonwebtoken');
app.get('/api/user', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const decoded = jwt.verify(token, jwks.publicKey); // From AS JWKS endpoint
res.json({ name: decoded.name });
});
4. PKCE (Proof Key for Code Exchange)
Prevents code interception (OAuth 2.1 mandatory for public clients). Client generates:
code_verifier: High-entropy secret (43-128 chars).
code_challenge = SHA256(verifier) base64url.
AS stores challenge, verifies verifier on /token.
Security: Mitigates auth code injection in browser redirects.
5. Refresh Tokens
RTs issue new ATs/RTs (rotation). Exact-as-heard (OAuth 2.1): AS echoes input client_id.
sequenceDiagram
Client->>AS: POST /token?grant_type=refresh_token&refresh_token=RT&client_id=xyz
AS->>Client: {access_token: NEW_AT, refresh_token: NEW_RT, expires_in}
JS Snippet:
const tokens = JSON.parse(localStorage.getItem('tokens'));
const res = await fetch('/token', {
method: 'POST',
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: tokens.refresh_token,
client_id: 'spa-client'
})
});
const newTokens = await res.json();
localStorage.setItem('tokens', JSON.stringify(newTokens));
Best Practice: RTs single-use/rotate; revoke on logout.
6. Browser Security
- HTTPS only (OAuth 2.1).
- State param: CSRF protection (random, validate on callback).
- Nonce (OIDC): Replay protection in ID Token.
- CORS: RS preflights; no AT in CORS unless
Authorization header allowed.
- Storage:
sessionStorage for AT (tab-specific); HttpOnly cookies for RT (server-side).
- Pushed Authorization Requests (PAR): POST auth params to AS first (anti-open-redirect).
- Vulnerabilities Fixed in 2.1: Mixing confidential/public clients, insecure redirect URIs.
State/Nonce JS:
const state = crypto.randomUUID();
sessionStorage.setItem('state', state);
const authUrl = `...&state=${state}`;
// Callback: if (urlParams.get('state') !== sessionStorage.getItem('state')) throw Error('CSRF');
7. Logout
OIDC supports:
- RP-Initiated Logout (front/back-channel).
- Front-Channel:
post_logout_redirect_uri + id_token_hint (browser redirect).
- Back-Channel: Server-to-server iframe ping.
sequenceDiagram
Client->>AS: GET /logout?post_logout_redirect_uri=...&id_token_hint=IDT
AS->>User: Clear session
AS->>Client: 302 to post_logout_redirect_uri
JS Logout:
const idToken = tokens.id_token;
window.location.href = `https://as.example.com/logout?id_token_hint=${idToken}&post_logout_redirect_uri=https://spa.example.com`;
localStorage.removeItem('tokens');
Session Management: Use check_session_iframe for silent renew/logout detection.
8. Best Practices (OAuth 2.1 Mandates)
- Always PKCE +
code flow for browsers/public clients.
- Short-lived ATs (<1h), RT rotation/revocation.
- JWT ATs with
aud validation on RS.
- Dynamic Client Registration with
client_id rotation.
- Sender-Constrained ATs (mTLS/DPoP) for binding.
- No browser localStorage for tokens (XSS risk); use memory or short-lived.
- Validate ALL params:
redirect_uri exact match, exp, aud, iss.
- Libraries: Auth0.js, oidc-client-js, or AppAuth.
- Compliance: Use OAuth 2.1 features like PAR, RAR (Request Object).
- Testing: Use tools like OAuth Playground, oidcdebugger.com.
For production, integrate with libraries like @auth0/auth0-spa-js. This covers the essentials—implement securely to avoid breaches like the 2023 OAuth attacks. Questions?