The Challenge: Securing Authentication in Single Page Applications
Single Page Applications (SPAs) have revolutionized web development, offering rich, dynamic user experiences. However, their client-side nature presents unique challenges for authentication, especially when interacting with OAuth 2.0. The traditional implicit flow, once popular for SPAs, has been deprecated due to security vulnerabilities, primarily its susceptibility to token interception and leakage via the browser's history or referrer headers.
Enter OAuth 2.0 with Proof Key for Code Exchange (PKCE, pronounced "pixy"). PKCE addresses the critical flaw of authorization code interception in public clients (like SPAs) by dynamically generating a secret for each authorization request. This guide will walk you through implementing PKCE end-to-end, ensuring your SPA authentication is robust and secure.
Understanding the OAuth 2.0 PKCE Flow
PKCE adds an extra layer of security to the Authorization Code flow by requiring the client to prove ownership of the authorization code. It achieves this using a cryptographic challenge and verifier pair:
code_verifier: A cryptographically random string generated by the client for each authorization request.code_challenge: A base64url-encoded SHA256 hash of thecode_verifier. This is sent to the authorization server during the initial authorization request.code_challenge_method: Specifies the hashing algorithm used (e.g.,S256for SHA256).
The flow proceeds as follows:
- The SPA generates a
code_verifierand its correspondingcode_challenge. - The SPA redirects the user to the Authorization Server, including the
code_challengeandcode_challenge_method. - The Authorization Server authenticates the user and, upon success, redirects back to the SPA's registered redirect URI with an
authorization_code. - The SPA (or a dedicated Backend-for-Frontend service) then sends a request to the Authorization Server's token endpoint, exchanging the
authorization_codefor access and refresh tokens. Crucially, this request must include the originalcode_verifier. - The Authorization Server verifies that the received
code_verifiermatches thecode_challengeit initially received. If they match, it issues the tokens.
This "proof of possession" ensures that even if an attacker intercepts the authorization_code, they cannot exchange it for tokens without the secret code_verifier, which was never transmitted to the attacker.
Client-Side Implementation (TypeScript)
Let's look at the core TypeScript code for handling PKCE in your SPA. We'll need a utility to generate the verifier and challenge, and then the logic to initiate the flow and handle the callback.
1. Generating code_verifier and code_challenge
First, a helper function to generate the random string and hash it:
// utils/pkce.ts
const generateRandomString = (length: number) => {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let text = '';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
const sha256 = async (plain: string) => {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const base64 = btoa(String.fromCharCode.apply(null, hashArray))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
return base64;
};
export const generatePkceCodes = async () => {
const verifier = generateRandomString(128); // 43-128 characters
const challenge = await sha256(verifier);
return { verifier, challenge };
};
The code_verifier should be between 43 and 128 characters long, consisting of unreserved URI characters. The code_challenge uses SHA256, which corresponds to the S256 challenge method.
2. Initiating the Authorization Flow
When the user clicks "Login", your SPA will generate the PKCE codes, store the code_verifier (e.g., in session storage or a secure cookie), and redirect the user.
// auth.ts (client-side)
import { generatePkceCodes } from './utils/pkce';
const CLIENT_ID = 'your-spa-client-id';
const REDIRECT_URI = 'http://localhost:3000/callback'; // Your SPA's callback URI
const AUTHORIZATION_ENDPOINT = 'https://your-auth-server.com/oauth2/authorize';
const SCOPE = 'openid profile email'; // Adjust scopes as needed
export const initiateLogin = async () => {
const { verifier, challenge } = await generatePkceCodes();
sessionStorage.setItem('pkce_code_verifier', verifier); // Store verifier securely
const params = new URLSearchParams({
response_type: 'code',
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: SCOPE,
code_challenge: challenge,
code_challenge_method: 'S256',
});
window.location.href = `${AUTHORIZATION_ENDPOINT}?${params.toString()}`;
};
Storing the code_verifier in sessionStorage is common for SPAs, as it's cleared when the session ends, limiting its lifetime. Ensure your SPA is served over HTTPS to protect against interception.
3. Handling the Callback and Token Exchange
After successful authentication, the Authorization Server redirects the user back to your REDIRECT_URI with an authorization_code in the query parameters. Your SPA must then retrieve this code and exchange it for actual access and refresh tokens.
A common pattern for SPAs is to have a dedicated backend service (a Backend-for-Frontend, or BFF) handle the token exchange. This keeps your client_secret (if applicable for confidential clients) secure and off the client-side. Even for public clients without a secret, a BFF can enhance security by acting as an intermediary for token management.
// auth.ts (client-side, continued)
const TOKEN_EXCHANGE_BFF_ENDPOINT = '/api/token-exchange'; // Your BFF endpoint
export const handleAuthCallback = async () => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const error = urlParams.get('error');
if (error) {
console.error('Authorization error:', error);
// Handle error, e.g., redirect to login page
return;
}
if (!code) {
console.error('No authorization code found.');
// Handle error
return;
}
const verifier = sessionStorage.getItem('pkce_code_verifier');
if (!verifier) {
console.error('PKCE code verifier not found.');
// This indicates a potential attack or session expiration
return;
}
sessionStorage.removeItem('pkce_code_verifier'); // Clear verifier after use
try {
const response = await fetch(TOKEN_EXCHANGE_BFF_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: code,
code_verifier: verifier,
redirect_uri: REDIRECT_URI, // Must match the one used in the auth request
}),
});
if (!response.ok) {
throw new Error(`Token exchange failed: ${response.statusText}`);
}
const tokens = await response.json();
console.log('Successfully obtained tokens:', tokens);
// Store tokens securely (e.g., in HTTP-only cookies via BFF)
// Redirect to application dashboard
window.location.href = '/dashboard';
} catch (err) {
console.error('Failed to exchange code for tokens:', err);
// Handle error
}
};
// In your SPA's router (e.g., React Router, Vue Router):
// If current path matches REDIRECT_URI, call handleAuthCallback()
The frontend now sends the authorization_code and code_verifier to your BFF, which will complete the actual token exchange with the Authorization Server.
Backend Token Exchange (Go Example with BFF Pattern)
Your Backend-for-Frontend (BFF) service acts as a secure intermediary. It receives the authorization_code and code_verifier from the SPA, adds its own client_id and client_secret (if applicable), and performs the POST request to the Authorization Server's token endpoint.
// main.go (BFF service)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
const (
AUTH_SERVER_TOKEN_ENDPOINT = "https://your-auth-server.com/oauth2/token"
CLIENT_ID = "your-bff-client-id" // Use a confidential client for BFF
CLIENT_SECRET = "your-bff-client-secret" // Keep this secret!
)
type TokenExchangeRequest struct {
Code string `json:"code"`
CodeVerifier string `json:"code_verifier"`
RedirectURI string `json:"redirect_uri"`
}
type TokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
IDToken string `json:"id_token"`
}
func enableCORS(w *http.ResponseWriter, r *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "http://localhost:3000") // Your SPA's origin
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
(*w).Header().Set("Access-Control-Allow-Headers", "Content-Type")
(*w).Header().Set("Access-Control-Allow-Credentials", "true") // Allow credentials for secure cookies
}
func tokenExchangeHandler(w http.ResponseWriter, r *http.Request) {
enableCORS(&w, r)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var reqBody TokenExchangeRequest
if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Prepare data for Authorization Server
form := map[string]string{
"grant_type": "authorization_code",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET, // Only for confidential clients. Public clients omit this.
"code": reqBody.Code,
"code_verifier": reqBody.CodeVerifier,
"redirect_uri": reqBody.RedirectURI,
}
formData := new(bytes.Buffer)
json.NewEncoder(formData).Encode(form) // Or use url.Values for application/x-www-form-urlencoded
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Post(AUTH_SERVER_TOKEN_ENDPOINT, "application/json", formData) // Adjust content type
if err != nil {
log.Printf("Error sending token request to Auth Server: %v", err)
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := ioutil.ReadAll(resp.Body)
log.Printf("Auth Server returned error: %d %s, Body: %s", resp.StatusCode, resp.Status, respBody)
http.Error(w, "Auth Server token exchange failed", resp.StatusCode)
return
}
var tokenResp TokenResponse
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
log.Printf("Error decoding token response: %v", err)
http.Error(w, "Failed to parse token response", http.StatusInternalServerError)
return
}
// For production, you'd set HTTP-only, Secure, SameSite=Lax/Strict cookies here
// and avoid sending tokens directly back to the client as JSON.
// For simplicity, we're returning JSON, but it's crucial to understand this
// is a simplification for demonstration.
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(tokenResp)
}
func main() {
http.HandleFunc("/api/token-exchange", tokenExchangeHandler)
log.Println("BFF service listening on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}
In a real-world BFF, you would not send the access_token and refresh_token directly back as JSON to the SPA. Instead, you would typically store the refresh_token in a secure, HTTP-only, encrypted cookie on the user's browser (or in a secure backend store) and issue short-lived access_tokens to the frontend, perhaps via a separate endpoint or by refreshing an existing session. The access_token can be stored in browser memory or an HTTP-only cookie, depending on your architecture and threat model. The `SameSite` attribute for cookies is crucial (Lax or Strict) to prevent CSRF attacks.
Key Security Considerations
code_verifierEntropy: Ensure yourcode_verifieris truly random and of sufficient length (43-128 characters) to prevent brute-force attacks.- HTTPS Everywhere: All communications, especially token exchanges and redirects, must occur over HTTPS. This protects against man-in-the-middle attacks.
- Redirect URI Validation: The Authorization Server must strictly validate the
redirect_uriagainst pre-registered values to prevent attackers from redirecting tokens to malicious sites. - State Parameter: While PKCE protects against authorization code interception, include a
stateparameter in your initial authorization request (and verify it on callback) to prevent CSRF attacks. This was omitted for brevity in the code examples but is essential. - Refresh Token Handling: If using refresh tokens, they should be stored securely (e.g., HTTP-only, secure cookies, or in a backend session) and rotated regularly. Only exchange refresh tokens via your secure BFF.
- Token Revocation: Implement token revocation mechanisms for scenarios like user logout or credential compromise.
- CORS Configuration: Your BFF must have proper CORS (Cross-Origin Resource Sharing) configurations to allow requests from your SPA's origin while blocking others.
- Error Handling and Logging: Robust error handling and logging are crucial for detecting and diagnosing authentication issues or potential attacks.
Key Takeaways
- OAuth 2.0 PKCE is the recommended and secure way to implement authentication for Single Page Applications (SPAs).
- PKCE protects against authorization code interception by requiring a
code_verifierduring token exchange, which matches a pre-sentcode_challenge. - A Backend-for-Frontend (BFF) pattern enhances security by handling the token exchange securely on the server-side, keeping client secrets (if any) out of the browser.
- Secure storage of tokens (especially refresh tokens) using HTTP-only, secure, and SameSite cookies is paramount.
- Always use HTTPS, validate redirect URIs strictly, and implement a
stateparameter for CSRF protection.
Be the first to leave a comment.
Leave a comment