7 min read
ā¢Question 24 of 28hardHow does OAuth 2.0 work?
Understanding OAuth 2.0 authorization.
What You'll Learn
- OAuth 2.0 roles
- Grant types
- Authorization Code flow
OAuth 2.0 Roles
- Resource Owner - User who owns data
- Client - App requesting access
- Authorization Server - Issues tokens
- Resource Server - Hosts protected data
Grant Types
| Grant Type | Use Case |
|---|---|
| Authorization Code | Web apps with backend |
| PKCE | Mobile/SPA apps |
| Client Credentials | Server-to-server |
| Refresh Token | Get new access token |
Authorization Code Flow
code.jsJavaScript
1. User clicks "Login with Google"
ā Redirect to Google
2. User authenticates & grants permission
ā Google redirects back with code
3. Backend exchanges code for tokens
ā POST to Google token endpoint
4. Use access token for API calls
ā GET /api/user with Bearer tokenImplementation
code.jsJavaScript
// Step 1: Redirect to auth provider
app.get('/auth/google', (req, res) => {
const url = `https://accounts.google.com/o/oauth2/v2/auth?
client_id=${CLIENT_ID}&
redirect_uri=${REDIRECT_URI}&
response_type=code&
scope=email profile`;
res.redirect(url);
});
// Step 2: Handle callback
app.get('/auth/callback', async (req, res) => {
const { code } = req.query;
// Step 3: Exchange code for tokens
const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
body: new URLSearchParams({
code,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
}),
});
const { access_token, refresh_token } = await tokenRes.json();
// Step 4: Get user info
const userRes = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${access_token}` },
});
const user = await userRes.json();
// Create session/JWT and redirect
});