10. OAuth2 Fundamentals
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.
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.
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
The Four OAuth2 Roles
Understanding these four roles is essential before writing any OAuth2 code.
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
OAuth2 Scopes
Scopes tell the user exactly what permissions the app is requesting. Users approve or deny specific scopes.
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
// 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.
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
Step 4 Details: Exchanging Code for Token
// 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.
// 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
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.
// 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 }) });
Knowledge Check
Ready to test your understanding of 10. OAuth2 Fundamentals?