πŸ”’ Security

OAuth 2.1

A security-hardened version of OAuth 2.0

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

// 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();
}

πŸ—£οΈ Examples of Practical Conversations

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

⚠️ Cautions

πŸ”— Related Terms

FIDO2 SAML JWT Token-based Auth OpenID Connect

πŸ“š Learn More

πŸ“„ IETF - OAuth 2.1 Draft Specification πŸ“„ OAuth.net - OAuth 2.1 Overview πŸ“„ RFC 7636 - PKCE Specification