OAuth2 Authentication
A comprehensive skill for implementing secure authentication and authorization using OAuth2 and OpenID Connect. This skill covers all major authorization flows, token management strategies, security best practices, and real-world implementation patterns for web, mobile, and API applications.
When to Use This Skill
Use this skill when:
- Implementing user authentication in web applications, SPAs, or mobile apps
- Building API authorization with access tokens and refresh tokens
- Integrating social login (Google, GitHub, Facebook, Twitter, etc.)
- Creating secure machine-to-machine (M2M) authentication
- Implementing single sign-on (SSO) across multiple applications
- Building an OAuth2 authorization server or identity provider
- Adding delegated authorization to allow third-party access
- Securing APIs with token-based authentication
- Implementing passwordless authentication flows
- Adding multi-tenant authentication with organization-specific rules
- Migrating from session-based to token-based authentication
- Implementing fine-grained access control with OAuth2 scopes
Core Concepts
OAuth2 Fundamentals
OAuth2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. It works by delegating user authentication to the service that hosts the user account and authorizing third-party applications to access that account.
Key Terminology:
- Resource Owner: The user who owns the data or resources
- Client: The application requesting access to resources (web app, mobile app, SPA)
- Authorization Server: Issues access tokens after authenticating the resource owner
- Resource Server: Hosts protected resources, accepts and validates access tokens
- Access Token: Short-lived credential used to access protected resources
- Refresh Token: Long-lived credential used to obtain new access tokens
- Scope: Permission granted to access specific resources or perform actions
- Authorization Code: Temporary code exchanged for an access token
- State Parameter: Prevents CSRF attacks during authorization flow
- Redirect URI: Callback URL where the user is redirected after authorization
OAuth2 Grant Types (Authorization Flows)
OAuth2 defines several grant types for different use cases:
1. Authorization Code Flow
Most Secure Flow - Recommended for Server-Side Applications
The authorization code flow is the most secure and widely used OAuth2 flow. It involves exchanging an authorization code for an access token on the server side.
Flow Steps:
- Client redirects user to authorization server with client_id, redirect_uri, scope, and state
- User authenticates and consents to requested permissions
- Authorization server redirects back to client with authorization code
- Client exchanges code for access token using client secret (server-side)
- Client uses access token to access protected resources
When to Use:
- Traditional server-side web applications
- Applications that can securely store client secrets
- When you need maximum security
- When refresh tokens are required
Security Benefits:
- Access token never exposed to browser
- Client authentication via client secret
- Authorization code is single-use and short-lived
- State parameter prevents CSRF attacks
2. Authorization Code Flow with PKCE
Secure Flow for Public Clients (SPAs and Mobile Apps)
PKCE (Proof Key for Code Exchange, pronounced "pixy") is an extension to the authorization code flow designed for public clients that cannot securely store client secrets.
Flow Steps:
- Client generates code_verifier (random string) and code_challenge (SHA256 hash)
- Client redirects to authorization server with code_challenge
- User authenticates and consents
- Authorization server returns authorization code
- Client exchanges code + code_verifier for access token
- Server validates code_verifier matches code_challenge
When to Use:
- Single Page Applications (SPAs)
- Mobile applications (iOS, Android)
- Desktop applications
- Any public client that cannot store secrets
Security Benefits:
- Prevents authorization code interception attacks
- No client secret required
- Protects against malicious apps intercepting redirect
- Recommended by OAuth2 security best practices (RFC 8252)
3. Client Credentials Flow
Machine-to-Machine Authentication
The client credentials flow is used when the client itself is the resource owner, typically for service-to-service communication.
Flow Steps:
- Client authenticates with client_id and client_secret
- Authorization server validates credentials
- Authorization server issues access token
- Client uses token to access protected resources
When to Use:
- Backend services communicating with APIs
- Cron jobs or scheduled tasks
- Microservices authentication
- CI/CD pipelines accessing APIs
- System-level operations without user context
Characteristics:
- No user involvement
- Client is the resource owner
- No refresh tokens (just request new access token)
- Typically long-lived or cached tokens
4. Implicit Flow (Deprecated)
Legacy Flow - No Longer Recommended
The implicit flow returns tokens directly in the URL fragment without an authorization code exchange. This flow is now considered insecure and should be avoided.
Why Deprecated:
- Access tokens exposed in browser history
- No client authentication
- No refresh token support
- Vulnerable to token theft
- Use Authorization Code Flow with PKCE instead
5. Resource Owner Password Credentials (ROPC)
Legacy Flow - Avoid Unless Necessary
The resource owner password credentials flow allows the client to collect username and password directly, then exchange them for tokens.
Flow Steps:
- User provides username and password to client
- Client sends credentials to authorization server
- Authorization server validates and issues tokens
When to Use (Rarely):
- First-party mobile apps migrating from legacy authentication
- Trusted first-party applications only
- When no browser/redirect flow is possible
Why to Avoid:
- Client handles user credentials directly (security risk)
- No multi-factor authentication support
- Phishing vulnerability
- Violates OAuth2 principle of delegated authorization
- Use Authorization Code Flow with PKCE instead when possible
6. Device Authorization Flow
For Input-Constrained Devices
The device flow is designed for devices with limited input capabilities (smart TVs, IoT devices, CLI tools).
Flow Steps:
- Device requests device code and user code from authorization server
- Device displays user code and instructs user to visit URL
- User visits URL on another device and enters user code
- User authenticates and authorizes device
- Device polls authorization server for access token
- Authorization server issues access token when user completes authorization
When to Use:
- Smart TVs and streaming devices
- IoT devices without keyboards
- CLI tools and command-line applications
- Gaming consoles
- Any device where typing is difficult
Token Types and Management
Access Tokens
Short-lived credentials for accessing protected resources
Characteristics:
- Typically expire in 15 minutes to 1 hour
- Bearer token format:
Authorization: Bearer <access_token> - Can be opaque tokens or JWTs (JSON Web Tokens)
- Should be treated as sensitive credentials
- Never log or expose in URLs
- Validate on every API request
JWT Structure (when using JWTs):
Header.Payload.Signature
JWT Payload Claims:
sub: Subject (user ID)iat: Issued at timeexp: Expiration timeiss: Issuer (authorization server)aud: Audience (resource server)scope: Granted permissions- Custom claims (user metadata, roles, etc.)
Token Validation:
- Verify signature using public key
- Check expiration (exp claim)
- Verify issuer (iss claim)
- Validate audience (aud claim)
- Check token has required scopes
Refresh Tokens
Long-lived credentials for obtaining new access tokens
Characteristics:
- Typically expire in days, weeks, or months
- Single-use or reusable (depending on implementation)
- Must be stored securely (never in localStorage in browsers)
- Should be encrypted at rest
- Can be revoked by authorization server
- Subject to rotation policies
Refresh Token Rotation:
- Each refresh issues a new refresh token
- Old refresh token is invalidated
- Prevents token replay attacks
- Detects token theft (multiple refresh attempts)
- Recommended security practice
Token Storage Best Practices:
Web Applications:
- Access tokens: Memory (React context, Vuex, Redux)
- Refresh tokens: HttpOnly, Secure, SameSite cookies
- Alternative: Store refresh token on backend, use session
Mobile Applications:
- Use platform secure storage
- iOS: Keychain Services
- Android: EncryptedSharedPreferences or Keystore
- Never store in plaintext files
SPAs:
- Store access tokens in memory only
- Use BFF (Backend for Frontend) pattern for refresh tokens
- Consider Token Handler pattern
- Avoid localStorage (XSS vulnerability)
ID Tokens (OpenID Connect)
Tokens containing user identity information
Characteristics:
- Always JWT format
- Contains user profile information
- Used for authentication (not authorization)
- Returned alongside access tokens
- Should be validated before use
Standard Claims:
sub: Subject (unique user ID)name: Full nameemail: Email addressemail_verified: Email verification statuspicture: Profile picture URLiat,exp: Issued/expiration times
OAuth2 Scopes
Fine-grained permissions for access control
Scopes define what access the client is requesting and what the access token permits.
Scope Naming Conventions:
read:users- Read user datawrite:users- Create/update usersdelete:users- Delete usersadmin:all- Full administrative accessopenid- Request OpenID Connect ID tokenprofile- Access user profile informationemail- Access user email address
Best Practices:
- Request minimum required scopes (principle of least privilege)
- Separate read and write permissions
- Create resource-specific scopes
- Document all available scopes
- Allow users to see and understand requested permissions
- Implement scope-based access control in APIs
Dynamic Scopes:
read:organization:{org_id}
write:project:{project_id}
admin:tenant:{tenant_id}
Security Considerations
State Parameter
Prevents Cross-Site Request Forgery (CSRF)
The state parameter is a random value that the client includes in the authorization request and validates in the callback.
Implementation:
- Generate random state value (cryptographically secure)
- Store state in session or encrypted cookie
- Include state in authorization URL
- Validate state matches when receiving callback
- Reject mismatched or missing state
Example State Value:
state: crypto.randomBytes(32).toString('hex')
// "7f8a3d9e2b1c4f5a6d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"
PKCE Implementation
Proof Key for Code Exchange - Prevents Code Interception
PKCE protects the authorization code flow against authorization code interception attacks.
Code Verifier:
- Random string, 43-128 characters
- Characters: A-Z, a-z, 0-9, -, ., _, ~
- Stored securely on client
Code Challenge:
- SHA256 hash of code verifier (recommended)
- Or plain code verifier (not recommended)
- Sent in authorization request
Code Challenge Methods:
S256: SHA256 hash (use this)plain: Plaintext verifier (legacy only)
Implementation Example:
// Generate code verifier
const codeVerifier = generateRandomString(64);
// Generate code challenge
const codeChallenge = base64UrlEncode(
sha256(codeVerifier)
);
// Store code verifier for token exchange
sessionStorage.setItem('code_verifier', codeVerifier);
// Include in authorization URL
const authUrl = `${authEndpoint}?` +
`client_id=${clientId}` +
`&redirect_uri=${redirectUri}` +
`&response_type=code` +
`&scope=${scopes}` +
`&state=${state}` +
`&code_challenge=${codeChallenge}` +
`&code_challenge_method=S256`;
Token Security
Protecting Access and Refresh Tokens
Do:
- Use HTTPS for all OAuth2 endpoints
- Store refresh tokens in secure storage only
- Implement token rotation
- Set appropriate token expiration times
- Validate tokens on every API request
- Use JWTs with strong signing algorithms (RS256, ES256)
- Implement token revocation
- Monitor for suspicious token usage
Don't:
- Store tokens in localStorage (XSS risk)
- Include tokens in URLs or query parameters
- Log tokens in application logs
- Use weak signing algorithms (HS256 with shared secrets)
- Share tokens between applications
- Extend access token lifetime unnecessarily
- Ignore token expiration
Redirect URI Validation
Prevent Open Redirect Vulnerabilities
Strict Validation Rules:
- Exact match required (no wildcards)
- Protocol must match exactly (https://)
- Host must match exactly
- Port must match (if specified)
- Path must match (if specified)
- Register all redirect URIs in advance
Mobile Deep Links:
- Use custom URL schemes:
com.example.app://callback - Or universal links (iOS):
https://example.com/auth/callback - Or app links (Android):
https://example.com/auth/callback - Register schemes with authorization server
Localhost Development:
- Allow http://localhost for development only
- Specify exact port:
http://localhost:3000/callback - Use 127.0.0.1 if localhost doesn't work
- Never use localhost redirects in production
OpenID Connect (OIDC)
Identity Layer Built on OAuth2
OpenID Connect adds an identity layer on top of OAuth2, providing authentication in addition to authorization.
Key Differences from OAuth2:
- Returns ID token in addition to access token
- ID token contains user identity information
- Standardized user info endpoint
- Standardized discovery endpoint (.well-known/openid-configuration)
- Session management capabilities
OIDC Flows:
Authorization Code Flow (recommended)
- Same as OAuth2 but returns id_token
- Most secure for web apps
Implicit Flow (deprecated)
- Returns id_token directly
- Insecure, use Code Flow with PKCE instead
Hybrid Flow
- Combines Code and Implicit flows
- Complex, rarely needed
OIDC Scopes:
openid(required) - Enables OIDCprofile- Name, picture, locale, etc.email- Email address and verification statusaddress- Physical addressphone- Phone number
UserInfo Endpoint:
GET /userinfo
Authorization: Bearer <access_token>
Response:
{
"sub": "248289761001",
"name": "Jane Doe",
"email": "jane@example.com",
"email_verified": true,
"picture": "https://example.com/photo.jpg"
}
ID Token Validation:
- Verify signature using provider's public key
- Validate issuer (iss claim)
- Validate audience (aud claim - should match client_id)
- Check expiration (exp claim)
- Validate nonce (if provided in request)
- Check token was issued recently (iat claim)
Multi-Tenancy Patterns
Organization-Specific Authentication
Many SaaS applications require users to authenticate within the context of an organization or tenant.
Patterns:
Organization Parameter
- Include organization ID in authorization request
scope=openid profile organization:acme-corp- Tokens scoped to specific organization
Organization Selector
- User selects organization after initial auth
- Exchange token for organization-specific token
- Support switching organizations
Custom Domain per Tenant
acme.example.comvsglobex.example.com- Separate OAuth2 configuration per tenant
- White-label authentication experience
Organization in Token Claims
- Include org_id in access token
- API validates organization access
- Support users in multiple organizations
Authorization Code Flow Implementation
Server-Side Web Application Flow
Complete implementation for traditional web applications with backend
Step 1: Configuration
// OAuth2 Configuration
const oauth2Config = {
clientId: process.env.OAUTH2_CLIENT_ID,
clientSecret: process.env.OAUTH2_CLIENT_SECRET,
authorizationEndpoint: 'https://auth.example.com/oauth/authorize',
tokenEndpoint: 'https://auth.example.com/oauth/token',
redirectUri: 'https://yourapp.com/auth/callback',
scopes: ['openid', 'profile', 'email', 'read:data'],
// Optional OIDC endpoints
userInfoEndpoint: 'https://auth.example.com/oauth/userinfo',
jwksUri: 'https://auth.example.com/.well-known/jwks.json',
// Security settings
useStateParameter: true,
usePKCE: false, // Not needed for confidential clients
};
Step 2: Generate Authorization URL
const crypto = require('crypto');
function generateAuthorizationUrl(req) {
// Generate and store state for CSRF protection
const state = crypto.randomBytes(32).toString('hex');
req.session.oauth2State = state;
// Build authorization URL
const params = new URLSearchParams({
client_id: oauth2Config.clientId,
redirect_uri: oauth2Config.redirectUri,
response_type: 'code',
scope: oauth2Config.scopes.join(' '),
state: state,
});
return `${oauth2Config.authorizationEndpoint}?${params.toString()}`;
}
// Express.js route
app.get('/auth/login', (req, res) => {
const authUrl = generateAuthorizationUrl(req);
res.redirect(authUrl);
});
Step 3: Handle Callback and Exchange Code
const axios = require('axios');
async function exchangeCodeForToken(code) {
const response = await axios.post(
oauth2Config.tokenEndpoint,
new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: oauth2Config.redirectUri,
client_id: oauth2Config.clientId,
client_secret: oauth2Config.clientSecret,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
return response.data;
// Returns: { access_token, refresh_token, token_type, expires_in, id_token }
}
// Callback route
app.get('/auth/callback', async (req, res) => {
const { code, state, error, error_description } = req.query;
// Check for authorization errors
if (error) {
console.error('Authorization error:', error, error_description);
return res.redirect('/auth/error?message=' + error_description);
}
// Validate state parameter (CSRF protection)
if (state !== req.session.oauth2State) {
console.error('State mismatch - possible CSRF attack');
return res.status(403).send('Invalid state parameter');
}
// Clear state from session
delete req.session.oauth2State;
try {
// Exchange authorization code for tokens
const tokens = await exchangeCodeForToken(code);
// Store tokens securely in session
req.session.accessToken = tokens.access_token;
req.session.refreshToken = tokens.refresh_token;
req.session.tokenExpiry = Date.now() + (tokens.expires_in * 1000);
// Optional: Fetch user info
if (tokens.id_token) {
const userInfo = await getUserInfo(tokens.access_token);
req.session.user = userInfo;
}
// Redirect to application
res.redirect('/dashboard');
} catch (error) {
console.error('Token exchange failed:', error);
res.redirect('/auth/error?message=Authentication failed');
}
});
Step 4: Use Access Token for API Requests
// Middleware to check authentication
function requireAuth(req, res, next) {
if (!req.session.accessToken) {
return res.redirect('/auth/login');
}
// Check if token is expired
if (Date.now() > req.session.tokenExpiry) {
// Token expired, try to refresh
return refreshAccessToken(req, res, next);
}
next();
}
// API request with access token
async function fetchUserData(accessToken) {
const response = await axios.get('https://api.example.com/user/data', {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
return response.data;
}
// Protected route
app.get('/dashboard', requireAuth, async (req, res) => {
try {
const userData = await fetchUserData(req.session.accessToken);
res.render('dashboard', { user: req.session.user, data: userData });
} catch (error) {
console.error('API request failed:', error);
res.status(500).send('Failed to fetch data');
}
});
Step 5: Implement Token Refresh
async function refreshAccessToken(req, res, next) {
if (!req.session.refreshToken) {
// No refresh token, require re-authentication
return res.redirect('/auth/login');
}
try {
const response = await axios.post(
oauth2Config.tokenEndpoint,
new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: req.session.refreshToken,
client_id: oauth2Config.clientId,
client_secret: oauth2Config.clientSecret,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
// Update tokens in session
req.session.accessToken = response.data.access_token;
req.session.tokenExpiry = Date.now() + (response.data.expires_in * 1000);
// Update refresh token if rotation is enabled
if (response.data.refresh_token) {
req.session.refreshToken = response.data.refresh_token;
}
next();
} catch (error) {
console.error('Token refresh failed:', error);
// Refresh failed, require re-authentication
delete req.session.accessToken;
delete req.session.refreshToken;
res.redirect('/auth/login');
}
}
Step 6: Implement Logout
app.post('/auth/logout', async (req, res) => {
// Optional: Revoke tokens on authorization server
if (req.session.accessToken) {
try {
await revokeToken(req.session.accessToken);
} catch (error) {
console.error('Token revocation failed:', error);
}
}
// Clear session
req.session.destroy((err) => {
if (err) {
console.error('Session destruction failed:', err);
}
res.redirect('/');
});
});
async function revokeToken(token) {
await axios.post(
'https://auth.example.com/oauth/revoke',
new URLSearchParams({
token: token,
client_id: oauth2Config.clientId,
client_secret: oauth2Config.clientSecret,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
}
PKCE Implementation (SPAs and Mobile Apps)
Single Page Application (React)
Complete OAuth2 with PKCE implementation for React SPAs
Setup and Configuration
// src/config/oauth2.js
export const oauth2Config = {
clientId: process.env.REACT_APP_OAUTH2_CLIENT_ID,
authorizationEndpoint: 'https://auth.example.com/oauth/authorize',
tokenEndpoint: 'https://auth.example.com/oauth/token',
redirectUri: window.location.origin + '/auth/callback',
scopes: ['openid', 'profile', 'email', 'read:data'],
audience: 'https://api.example.com',
};
// PKCE utility functions
export function generateRandomString(length) {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const values = crypto.getRandomValues(new Uint8Array(length));
return Array.from(values)
.map(v => charset[v % charset.length])
.join('');
}
export async function generateCodeChallenge(codeVerifier) {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return base64UrlEncode(digest);
}
export function base64UrlEncode(buffer) {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
Auth Context Provider
// src/contexts/AuthContext.js
import React, { createContext, useState, useContext, useEffect } from 'react';
import { oauth2Config, generateRandomString, generateCodeChallenge } from '../config/oauth2';
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [accessToken, setAccessToken] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Check for existing session
checkAuth();
}, []);
async function checkAuth() {
// Try to restore access token from memory or refresh
const storedToken = sessionStorage.getItem('access_token');
const expiresAt = sessionStorage.getItem('expires_at');
if (storedToken && expiresAt && Date.now() < parseInt(expiresAt)) {
setAccessToken(storedToken);
await fetchUserInfo(storedToken);
} else {
// Token expired or doesn't exist, try refresh
await tryRefresh();
}
setLoading(false);
}
async function login() {
// Generate PKCE parameters
const codeVerifier = generateRandomString(64);
const codeChallenge = await generateCodeChallenge(codeVerifier);
const state = generateRandomString(32);
// Store for callback
sessionStorage.setItem('code_verifier', codeVerifier);
sessionStorage.setItem('oauth2_state', state);
// Build authorization URL
const params = new URLSearchParams({
client_id: oauth2Config.clientId,
redirect_uri: oauth2Config.redirectUri,
response_type: 'code',
scope: oauth2Config.scopes.join(' '),
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
// Redirect to authorization server
window.location.href = `${oauth2Config.authorizationEndpoint}?${params}`;
}
async function handleCallback(code, state) {
// Validate state
const savedState = sessionStorage.getItem('oauth2_state');
if (state !== savedState) {
throw new Error('Invalid state parameter - possible CSRF attack');
}
// Get code verifier
const codeVerifier = sessionStorage.getItem('code_verifier');
if (!codeVerifier) {
throw new Error('Code verifier not found');
}
// Exchange code for tokens
const response = await fetch(oauth2Config.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: oauth2Config.redirectUri,
client_id: oauth2Config.clientId,
code_verifier: codeVerifier,
}),
});
if (!response.ok) {
throw new Error('Token exchange failed');
}
const tokens = await response.json();
// Store tokens
setAccessToken(tokens.access_token);
sessionStorage.setItem('access_token', tokens.access_token);
sessionStorage.setItem('expires_at', Date.now() + (tokens.expires_in * 1000));
// Store refresh token in httpOnly cookie via backend
if (tokens.refresh_token) {
await storeRefreshToken(tokens.refresh_token);
}
// Fetch user info
await fetchUserInfo(tokens.access_token);
// Clean up
sessionStorage.removeItem('code_verifier');
sessionStorage.removeItem('oauth2_state');
}
async function fetchUserInfo(token) {
const response = await fetch('https://auth.example.com/oauth/userinfo', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.ok) {
const userInfo = await response.json();
setUser(userInfo);
}
}
async function storeRefreshToken(refreshToken) {
// Store refresh token via backend (httpOnly cookie)
await fetch('/api/auth/store-refresh-token', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refreshToken }),
});
}
async function tryRefresh() {
try {
// Call backend to refresh using httpOnly cookie
const response = await fetch('/api/auth/refresh', {
method: 'POST',
credentials: 'include',
});
if (response.ok) {
const tokens = await response.json();
setAccessToken(tokens.access_token);
sessionStorage.setItem('access_token', tokens.access_token);
sessionStorage.setItem('expires_at', Date.now() + (tokens.expires_in * 1000));
await fetchUserInfo(tokens.access_token);
return true;
}
} catch (error) {
console.error('Token refresh failed:', error);
}
return false;
}
async function logout() {
// Revoke tokens
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
});
// Clear state
setUser(null);
setAccessToken(null);
sessionStorage.clear();
}
const value = {
user,
accessToken,
loading,
login,
logout,
handleCallback,
isAuthenticated: !!accessToken,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
Callback Component
// src/components/AuthCallback.js
import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
export function AuthCallback() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useAuth();
const [error, setError] = useState(null);
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const errorParam = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
if (errorParam) {
setError(errorDescription || errorParam);
return;
}
if (code && state) {
handleCallback(code, state)
.then(() => {
navigate('/dashboard');
})
.catch((err) => {
console.error('Authentication failed:', err);
setError(err.message);
});
} else {
setError('Missing authorization code or state');
}
}, [searchParams, handleCallback, navigate]);
if (error) {
return (
<div className="auth-error">
<h2>Authentication Failed</h2>
<p>{error}</p>
<button => navigate('/')}>Return Home</button>
</div>
);
}
return (
<div className="auth-loading">
<h2>Completing authentication...</h2>
<div className="spinner"></div>
</div>
);
}
Protected Route Component
// src/components/ProtectedRoute.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
export function ProtectedRoute({ children }) {
const { isAuthenticated, loading } = useAuth();
if (loading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return children;
}
API Client with Token Management
// src/utils/apiClient.js
import { oauth2Config } from '../config/oauth2';
class ApiClient {
constructor() {
this.baseUrl = 'https://api.example.com';
}
async request(endpoint, options = {}) {
const accessToken = sessionStorage.getItem('access_token');
const expiresAt = sessionStorage.getItem('expires_at');
// Check if token needs refresh
if (!accessToken || Date.now() >= parseInt(expiresAt)) {
await this.refreshToken();
}
const token = sessionStorage.getItem('access_token');
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (response.status === 401) {
// Token invalid, try refresh once
await this.refreshToken();
const newToken = sessionStorage.getItem('access_token');
// Retry request
const retryResponse = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${newToken}`,
'Content-Type': 'application/json',
},
});
if (!retryResponse.ok) {
throw new Error('API request failed after token refresh');
}
return retryResponse.json();
}
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
}
async refreshToken() {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
credentials: 'include',
});
if (!response.ok) {
// Refresh failed, redirect to login
window.location.href = '/login';
throw new Error('Token refresh failed');
}
const tokens = await response.json();
sessionStorage.setItem('access_token', tokens.access_token);
sessionStorage.setItem('expires_at', Date.now() + (tokens.expires_in * 1000));
}
async get(endpoint) {
return this.request(endpoint);
}
async post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data),
});
}
async put(endpoint, data) {
return this.request(endpoint, {
method: 'PUT',
body: JSON.stringify(data),
});
}
async delete(endpoint) {
return this.request(endpoint, {
method: 'DELETE',
});
}
}
export const apiClient = new ApiClient();
Client Credentials Flow
Backend Service Authentication
Machine-to-machine authentication for services and APIs
Node.js Implementation
// Service-to-service authentication
class OAuth2Client {
constructor(config) {
this.clientId = config.clientId;
this.clientSecret = config.clientSecret;
this.tokenEndpoint = config.tokenEndpoint;
this.audience = config.audience;
this.scopes = config.scopes || [];
this.accessToken = null;
this.tokenExpiry = null;
}
async getAccessToken() {
// Return cached token if still valid
if (this.accessToken && Date.now() < this.tokenExpiry - 60000) {
return this.accessToken;
}
// Request new token
const response = await fetch(this.tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
audience: this.audience,
scope: this.scopes.join(' '),
}),
});
if (!response.ok) {
throw new Error('Failed to obtain access token');
}
const data = await response.json();
// Cache token
this.accessToken = data.access_token;
this.tokenExpiry = Date.now() + (data.expires_in * 1000);
return this.accessToken;
}
async callApi(endpoint, options = {}) {
const token = await this.getAccessToken();
const response = await fetch(endpoint, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${token}`,
},
});
if (response.status === 401) {
// Token might be invalid, force refresh and retry
this.accessToken = null;
const newToken = await this.getAccessToken();
const retryResponse = await fetch(endpoint, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${newToken}`,
},
});
return retryResponse;
}
return response;
}
}
// Usage
const oauth2Client = new OAuth2Client({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
tokenEndpoint: 'https://auth.example.com/oauth/token',
audience: 'https://api.example.com',
scopes: ['read:data', 'write:data'],
});
// Make API calls
async function fetchData() {
const response = await oauth2Client.callApi('https://api.example.com/data');
return response.json();
}
Python Implementation
# client_credentials_oauth2.py
import requests
import time
from datetime import datetime, timedelta
class OAuth2Client:
def __init__(self, client_id, client_secret, token_endpoint, audience=None, scopes=None):
self.client_id = client_id
self.client_secret = client_secret
self.token_endpoint = token_endpoint
self.audience = audience
self.scopes = scopes or []
self.access_token = None
self.token_expiry = None
def get_access_token(self):
"""Get cached token or request new one"""
# Return cached token if valid
if self.access_token and datetime.now() < self.token_expiry - timedelta(minutes=1):
return self.access_token
# Request new token
data = {
'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_secret,
}
if self.audience:
data['audience'] = self.audience
if self.scopes:
data['scope'] = ' '.join(self.scopes)
response = requests.post(
self.token_endpoint,
data=data,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
if not response.ok:
raise Exception(f'Failed to obtain access token: {response.text}')
token_data = response.json()
# Cache token
self.access_token = token_data['access_token']
self.token_expiry = datetime.now() + timedelta(seconds=token_data['expires_in'])
return self.access_token
def call_api(self, url, method='GET', **kwargs):
"""Make authenticated API request"""
token = self.get_access_token()
headers = kwargs.pop('headers', {})
headers['Authorization'] = f'Bearer {token}'
response = requests.request(method, url, headers=headers, **kwargs)
# Handle token expiration
if response.status_code == 401:
# Force token refresh and retry
self.access_token = None
token = self.get_access_token()
headers['Authorization'] = f'Bearer {token}'
response = requests.request(method, url, headers=headers, **kwargs)
return response
# Usage
client = OAuth2Client(
client_id='your_client_id',
client_secret='your_client_secret',
token_endpoint='https://auth.example.com/oauth/token',
audience='https://api.example.com',
scopes=['read:data', 'write:data']
)
# Make API requests
response = client.call_api('https://api.example.com/data')
data = response.json()
OpenID Connect Implementation
Complete OIDC Integration
Authentication with identity verification
ID Token Validation
// id-token-validator.js
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
class IDTokenValidator {
constructor(config) {
this.issuer = config.issuer;
this.audience = config.audience;
this.jwksUri = config.jwksUri;
// JWKS client for fetching public keys
this.client = jwksClient({
jwksUri: this.jwksUri,
cache: true,
cacheMaxAge: 86400000, // 24 hours
});
}
async getSigningKey(kid) {
const key = await this.client.getSigningKey(kid);
return key.getPublicKey();
}
async validate(idToken) {
try {
// Decode token header to get key ID
const decoded = jwt.decode(idToken, { complete: true });
…(truncated)