Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

OAuth 2.0 and OpenID Connect Explained

A developer's guide to OAuth 2.0 and OpenID Connect: roles, the authorization code flow with PKCE, access, refresh and ID tokens, JWT validation, scopes, other grant types and security best practices.

Sumit KumarUpdated Oct 11, 20264 min readSystem Design
OAuth 2.0 and OpenID Connect Explained

Every "Sign in with Google" button and every app that asks to "access your calendar" relies on OAuth 2.0. Add OpenID Connect (OIDC) on top and you get standard login. Understanding these two protocols is essential for building secure web, mobile and API backends.

Authorization vs authentication#

OAuth 2.0OpenID Connect
Question it answers"What is this app allowed to do?" (authorization)"Who is the user?" (authentication)
Main tokenAccess tokenID token (a JWT) plus access token
ExampleA photo printing app reads your Google Photos"Sign in with Google" on a website
Don't use an access token as proof of login

Access tokens are meant for APIs, not for the client to identify the user. Use OIDC's ID token for authentication.

The four roles#

  • Resource owner: the user who owns the data.
  • Client: the application that wants access (your web, mobile or SPA app).
  • Authorization server: authenticates the user and issues tokens (Google, Auth0, Keycloak, Okta, Microsoft Entra ID).
  • Resource server: the API that holds the data and accepts access tokens.

The authorization code flow with PKCE#

This is the recommended flow for almost every app today, including single-page and mobile apps.

OAuth 2.0 authorization code flow with PKCE: the user, client app, authorization server and resource server exchanging an authorization code for access and ID tokens
  1. The client creates a random code_verifier and its SHA-256 hash, the code_challenge.
  2. The client redirects the user to the authorization server with the challenge, requested scopes and a random state.
  3. The user logs in and approves the requested permissions (consent).
  4. The authorization server redirects back with a short-lived authorization code.
  5. The client exchanges the code plus the original code_verifier for tokens.
  6. The client calls the API with the access token in the Authorization header.

Step 1–2: build the authorization request#

JavaScript
// Generate PKCE values in the browser
function base64url(bytes) {
  return btoa(String.fromCharCode(...new Uint8Array(bytes)))
    .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = base64url(
  await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
);
const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
sessionStorage.setItem("pkce_verifier", verifier);
sessionStorage.setItem("oauth_state", state);

const params = new URLSearchParams({
  response_type: "code",
  client_id: "my-app",
  redirect_uri: "https://app.example.com/callback",
  scope: "openid profile email",
  state,
  code_challenge: challenge,
  code_challenge_method: "S256",
});
location.href = `https://auth.example.com/authorize?${params}`;

Step 4: the callback#

HTTP
GET https://app.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=af0ifjsldkj

Step 5: exchange the code for tokens#

HTTP
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https://app.example.com/callback
&client_id=my-app
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
JSON
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "8xLOxBtZp8",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid profile email"
}
Why PKCE?

If an attacker intercepts the authorization code, they still can't redeem it without the secret code_verifier, which never left the client. The state parameter separately protects against CSRF on the callback.

The three token types#

TokenPurposeLifetimeSent to
Access tokenCall protected APIsShort (5–60 min)Resource server
Refresh tokenGet new access tokens without re-loginLong (days to months), often rotatedAuthorization server only
ID token (OIDC)Tells the client who logged inShortNever sent to APIs; read by the client

Inside a JWT#

Tokens are often JSON Web Tokens: header.payload.signature, each part base64url-encoded.

JSON
// Decoded ID token payload
{
  "iss": "https://auth.example.com",
  "sub": "248289761001",
  "aud": "my-app",
  "exp": 1760200000,
  "iat": 1760196400,
  "nonce": "n-0S6_WzA2Mj",
  "email": "asha@example.com",
  "name": "Asha Verma"
}

Validating tokens on the API#

JavaScript
// npm install jose
import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(
  new URL("https://auth.example.com/.well-known/jwks.json")
);

export async function requireAuth(req, res, next) {
  const token = req.headers.authorization?.replace(/^Bearer /, "");
  if (!token) return res.status(401).json({ error: "missing token" });
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: "https://auth.example.com",
      audience: "orders-api",
    });
    if (!payload.scope?.split(" ").includes("orders:read")) {
      return res.status(403).json({ error: "insufficient scope" });
    }
    req.user = payload;
    next();
  } catch {
    res.status(401).json({ error: "invalid token" });
  }
}

Always check the signature, issuer, audience and expiry, then enforce scopes. For opaque (non-JWT) tokens, call the authorization server's introspection endpoint instead.

Other grant types#

GrantUse it forStatus
Authorization code + PKCEWeb, SPA, mobile and desktop apps with a userRecommended
Client credentialsService-to-service calls with no userRecommended
Device authorizationSmart TVs, CLIs and devices without a browserRecommended
Refresh tokenRenewing access tokensRecommended (with rotation)
ImplicitOld SPAs: tokens in the URL fragmentDeprecated
Resource owner passwordApp collects the user's password directlyDeprecated
Bash
# Client credentials: a backend job calling another service
curl -X POST https://auth.example.com/token \
  -d grant_type=client_credentials \
  -d client_id=report-worker \
  -d client_secret=$CLIENT_SECRET \
  -d scope=orders:read

Security best practices#

  • Use authorization code + PKCE for every user-facing client; never use implicit or password grants.
  • Register exact redirect URIs; never allow wildcards.
  • Always send and verify state (and nonce for OIDC).
  • Keep access tokens short-lived and rotate refresh tokens.
  • In browsers, prefer a backend-for-frontend that stores tokens server-side with HttpOnly, Secure, SameSite cookies, rather than putting tokens in localStorage.
  • Request the minimum scopes you need.
  • Use HTTPS everywhere.

Token validation fits naturally into an API gateway in front of your microservices. For handling API errors on the client, see Fetch API error handling.

Key takeaways#

  • OAuth 2.0 handles authorization (what an app can access); OpenID Connect adds authentication (who the user is).
  • Authorization code flow with PKCE is the recommended flow for web, SPA and mobile apps.
  • Access tokens call APIs, refresh tokens renew them, and ID tokens identify the user to the client.
  • APIs must verify a JWT's signature, issuer, audience, expiry and scopes.
  • Avoid the implicit and password grants, use exact redirect URIs and keep tokens out of insecure storage.