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

