Script Valley
Authentication From Scratch
OAuth 2.0 and Social LoginLesson 4.1

How OAuth 2.0 authorization code flow works

OAuth 2.0 roles, authorization server, resource server, client, authorization code, access token, redirect URI, state parameter, PKCE

Four Roles, One Flow

OAuth 2.0 lets users grant your app access to their data on another service without giving you their password. The four roles are: Resource Owner (the user), Client (your app), Authorization Server (Google's login server), and Resource Server (Google's API).

The Authorization Code Flow

  1. User clicks "Login with Google" on your app
  2. Your app redirects to Google's authorization URL with your client_id, scope, redirect_uri, and a random state value
  3. User logs in to Google and grants permission
  4. Google redirects back to your redirect_uri with an authorization code and the state value
  5. Your server exchanges the code for an access token via a server-to-server POST request
  6. You use the access token to fetch the user's profile from Google's API

The State Parameter

The state value you generate in step 2 must be validated when it comes back in step 4. This prevents CSRF attacks on the OAuth callback — an attacker cannot forge a callback without knowing your randomly generated state. Store it in the session before the redirect; compare it on callback.

PKCE

PKCE (Proof Key for Code Exchange) adds protection against authorization code interception in public clients (mobile apps, SPAs). It is now recommended for all OAuth flows, including server-side apps.

Up next

Setting up Google OAuth with Passport.js

Sign in to track progress