OAuth 2.1
A security-hardened version of OAuth 2.0
A security-hardened version of OAuth 2.0
OAuth 2.1 is the latest authorization framework that consolidates the security best practices (BCP) of OAuth 2.0 and removes features that are no longer secure. It is based on RFC 6749 (OAuth 2.0), but it completely removes the Implicit Grant and the Resource Owner Password Credentials Grant and requires PKCE.
The key change in OAuth 2.1 is making PKCE (Proof Key for Code Exchange) mandatory. In the Authorization Code Flow, code_verifier and code_challenge are used to prevent Authorization Code Interception attacks. Previously it was recommended only for public clients, but it is now required for all clients.
The Implicit Grant (response_type=token) was removed because the token is exposed in the URL fragment and can leak through browser history and the Referer header. Authorization Code + PKCE is used instead. The Password Grant was removed because it is a security risk for a client to handle the user's password directly.
Refresh Token Rotation is also recommended. When a Refresh Token is used, a new Refresh Token is issued and the previous one is invalidated, limiting the abuse of a stolen token. A shorter expiration time (on the order of minutes) is recommended for the Access Token, which is renewed using the Refresh Token.
// OAuth 2.1 Authorization Code Flow with PKCE
// 1. PKCE code_verifier μμ± (43-128μ λλ€ λ¬Έμμ΄)
function generateCodeVerifier(): string {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return base64URLEncode(array);
}
// 2. code_challenge μμ± (S256 λ°©μ κΆμ₯)
async function generateCodeChallenge(verifier: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const hash = await crypto.subtle.digest('SHA-256', data);
return base64URLEncode(new Uint8Array(hash));
}
// 3. Authorization μμ² μμ
async function startOAuth() {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
const state = crypto.randomUUID(); // CSRF λ°©μ§
// μΈμ
/λ‘컬 μ€ν 리μ§μ μ μ₯ (ν ν° κ΅ν μ νμ)
sessionStorage.setItem('oauth_code_verifier', codeVerifier);
sessionStorage.setItem('oauth_state', state);
const params = new URLSearchParams({
response_type: 'code', // Implicit(token) λμ νμ code
client_id: 'YOUR_CLIENT_ID',
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile email',
state: state,
code_challenge: codeChallenge, // PKCE νμ
code_challenge_method: 'S256' // S256 κΆμ₯, plainμ λΉκΆμ₯
});
window.location.href = `https://auth.example.com/authorize?${params}`;
}
// 4. Callbackμμ ν ν° κ΅ν
async function handleCallback() {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
// State κ²μ¦ (CSRF λ°©μ§)
if (state !== sessionStorage.getItem('oauth_state')) {
throw new Error('Invalid state - possible CSRF attack');
}
const codeVerifier = sessionStorage.getItem('oauth_code_verifier');
// ν ν° μλν¬μΈνΈμ code + code_verifier μ μ‘
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: 'https://app.example.com/callback',
client_id: 'YOUR_CLIENT_ID',
code_verifier: codeVerifier // PKCE κ²μ¦
})
});
const tokens = await response.json();
// { access_token, refresh_token, id_token, expires_in }
// μ 리
sessionStorage.removeItem('oauth_code_verifier');
sessionStorage.removeItem('oauth_state');
return tokens;
}
// 5. Refresh Token Rotation
async function refreshTokens(refreshToken: string) {
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: 'YOUR_CLIENT_ID'
})
});
// μ access_token + μ refresh_token λ°ν (Rotation)
return response.json();
}
In a security review:
"We're using the Implicit Flow in our existing OAuth 2.0 implementation, but we need to migrate to OAuth 2.1. Add PKCE and remove Implicit. The SPA also needs to switch to Authorization Code + PKCE."
In a technical interview:
"Why is PKCE needed?" - "Even if the Authorization Code is stolen, the token exchange can't be completed without the code_verifier. In particular, with a custom URL scheme redirect in a mobile app, another app could intercept the code, and PKCE prevents this."
In API design:
"How should I set the Access Token expiration time?" - "In OAuth 2.1, it's recommended to set it short (5-15 minutes). Renew it with the Refresh Token, and minimize the impact of theft with Refresh Token Rotation."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free