4 Hours

10. OAuth2 Fundamentals

OAuth2

OAuth2 is the industry-standard protocol for authorization. It allows users to grant third-party applications limited access to their resources without sharing passwords. This module explains OAuth2 one concept at a time.

Important: OAuth2 is for AUTHORIZATION (what you can do), not authentication (who you are). OAuth2 delegates access; OIDC (OpenID Connect) adds authentication.

The Problem OAuth2 Solves

Imagine you want an app to access your Google Photos. The naive approach is giving the app your Google password — extremely dangerous.

Text
Giving password = BAD:
- App gets FULL access to your entire Google account
- You cannot limit what the app can do
- You cannot revoke access without changing password

OAuth2 = GOOD:
- App gets a LIMITED token (read-only, specific photos)
- You approve exactly what permissions to grant
- You can revoke access anytime
Analogy: OAuth2 is like a hotel key card. It only opens your room (limited scope), expires after checkout (time-bound), and can be revoked.

The Four OAuth2 Roles

Understanding these four roles is essential before writing any OAuth2 code.

Text
1. Resource Owner (The User)
   - The person who owns the data
   - Example: You, the Google Photos user

2. Client (The Application)
   - The app requesting access
   - Example: A photo printing service

3. Authorization Server
   - Issues tokens after user consent
   - Example: Google's OAuth2 server (accounts.google.com)

4. Resource Server
   - Hosts the user's data
   - Example: Google Photos API server
Remember: The Authorization Server and Resource Server are often separate services.

OAuth2 Scopes

Scopes tell the user exactly what permissions the app is requesting. Users approve or deny specific scopes.

Text
Common Scope Examples:
- read:user     → Can read your profile
- write:user    → Can update your profile
- read:photos   → Can view your photos
- write:photos  → Can upload photos
- delete:photos → Can delete photos
- offline_access → Can get a refresh token
JavaScript
// Client requests specific scopes
const authUrl = 'https://auth.myapp.com/authorize?' +
    'scope=read:user read:photos' +
    '&response_type=code';

// User sees: "This app wants to read your profile and photos"
// User does NOT see any request to write or delete

The Authorization Code Flow (Step by Step)

This is the most secure OAuth2 flow. Let's break it down into 5 steps.

Text
STEP 1: Client redirects user to Authorization Server
GET /authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK&scope=read&state=RANDOM

STEP 2: User logs in and grants permission
Authorization Server shows consent screen

STEP 3: Authorization Server redirects back with code
Location: https://myapp.com/callback?code=AUTH_CODE&state=RANDOM

STEP 4: Client exchanges code for tokens (server-to-server)
POST /token grant_type=authorization_code&code=AUTH_CODE

STEP 5: Client uses access token to call Resource Server
Authorization: Bearer ACCESS_TOKEN
Why a code and not the token directly? The code goes through the browser (less secure). The token exchange is server-to-server (more secure).

Step 4 Details: Exchanging Code for Token

JavaScript
// Server-side call (NOT in browser!)
const response = await fetch('https://auth.myapp.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
        grant_type: 'authorization_code',
        code: authCode,
        redirect_uri: 'https://myapp.com/callback',
        client_id: 'abc123',
        client_secret: 'super-secret'  // Only known to server
    })
});

const { access_token, refresh_token, expires_in } = await response.json();

Refresh Tokens in OAuth2

Access tokens expire quickly (usually 1 hour). Refresh tokens are long-lived and can get new access tokens without user interaction.

JavaScript
// When access token expires
async function refreshAccessToken(refreshToken) {
    const response = await fetch('https://auth.myapp.com/token', {
        method: 'POST',
        body: new URLSearchParams({
            grant_type: 'refresh_token',
            refresh_token: refreshToken,
            client_id: 'abc123'
        })
    });

    const { access_token, expires_in } = await response.json();
    return access_token;
}

// User never needs to log in again until refresh token expires
Refresh tokens are powerful! Store them securely (httpOnly cookies, never localStorage).

PKCE: Securing Mobile & SPAs

Mobile apps and single-page apps cannot keep client secrets secure. PKCE solves this with a one-time secret per request.

JavaScript
// Step 1: Generate code verifier and challenge
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto.createHash('sha256')
    .update(codeVerifier)
    .digest('base64url');

// Step 2: Send code_challenge with auth request
const authUrl = '/authorize?' +
    'code_challenge=' + codeChallenge +
    '&code_challenge_method=S256';

// Step 3: When exchanging code, send code_verifier
await fetch('/token', {
    method: 'POST',
    body: new URLSearchParams({
        grant_type: 'authorization_code',
        code: authCode,
        code_verifier: codeVerifier  // Proves it's the same app
    })
});
Why PKCE matters: Without PKCE, a malicious app could intercept the authorization code. PKCE ensures only the app that started the flow can complete it.

Knowledge Check

Ready to test your understanding of 10. OAuth2 Fundamentals?

Back