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

