#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
•Question 24 of 28hard

How 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 TypeUse Case
Authorization CodeWeb apps with backend
PKCEMobile/SPA apps
Client CredentialsServer-to-server
Refresh TokenGet 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 token

Implementation

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
});