OAuth 2.0 Introduction
OAuth 2.0 is an authorization framework that allows third-party applications to access user resources without sharing credentials.
The OAuth Problem
Without OAuth:
App wants to access your Google Calendar
โ You give app your Google password
โ App has full access to your entire Google account
With OAuth:
App wants to access your Google Calendar
โ Google asks: "Allow this app to view your calendar?"
โ You approve
โ App gets limited access token
โ Your password stays with Google
Key Concepts
Roles
| Role | Description |
|---|---|
| Resource Owner | The user who owns the data |
| Client | The application requesting access |
| Authorization Server | Issues tokens (e.g., Google) |
| Resource Server | Hosts the protected resources |
Tokens
| Token | Purpose | Lifetime |
|---|---|---|
| Access Token | Access resources | Short (minutes/hours) |
| Refresh Token | Get new access tokens | Long (days/months) |
Scopes
Scopes limit what the client can access:
scope=read:email read:profile
scope=calendar:read calendar:write
OAuth Flows
Authorization Code Flow (Most Common)
For server-side applications with a backend.
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ User โ โ Client โ
โ (Browser)โ โ (Your App) โ
โโโโโโฌโโโโโโ โโโโโโโโโฌโโโโโโโโ
โ โ
โ 1. Click "Login with Google" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโบโ
โ โ
โ 2. Redirect to Google โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ 3. User logs in & approves โ
โโโโโโโโโโโโโโโบโโโโโโโโโโโโโโโโโโโโโดโโโ
โ โ Auth Server โ
โ 4. Redirect โ (Google) โ
โ with code โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ 5. Send code to backend โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโบโ
โ โ
โ 6. Exchange code โ
โ for tokens โ
โ โโโโโโโโโโโโโโโโโโโบ Auth Server
โ โโโโโโโโโโโโโโโโโโโ
โ โ
โ 7. User is logged in โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Exercise: OAuth URL Builder
Loading JavaScript Exercise...
Token Exchange
After getting the authorization code, exchange it for tokens:
POST /oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=AUTH_CODE_HERE
&redirect_uri=https://myapp.com/callback
&client_id=CLIENT_ID
&client_secret=CLIENT_SECRET
Response:
{
"access_token": "eyJ...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "dGhpc..."
}
Security Best Practices
1. Use State Parameter
Prevents CSRF attacks:
const state = crypto.randomBytes(16).toString('hex');
// Store state, verify on callback
2. Use PKCE for Public Clients
For mobile apps and SPAs:
const codeVerifier = generateRandomString(128);
const codeChallenge = base64UrlEncode(sha256(codeVerifier));
3. Validate Tokens
Always verify the access token before trusting it.
4. Use Minimal Scopes
Only request the permissions you need.
Summary
OAuth 2.0:
- Enables secure third-party access
- Uses access tokens instead of passwords
- Supports different flows for different app types
- Requires careful security implementation
Up next ยท Lesson 26 of 37
Why Version Your API
2 min read
25 of 37 lessons done

