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

