Lesson 8 of 8 · 15 min · Authentication

OAuth and OpenID Connect login, and protecting routes

Covers: Express 5 on Node.js 22 or newer. Updated 13 Nov 2026. Part of the Full Stack Developer roadmap.

What you will learn

  • What OAuth 2.0 and OpenID Connect (OIDC) are, and why use "Sign in with Google"
  • The authorization code flow with PKCE, step by step
  • Handle the redirect and callback safely (state, nonce, validation)
  • Protect routes with authentication middleware and role checks
  • Prevent the most common authorisation bug: access to other users' data

In simple words

Instead of making every website store a new password, "Sign in with Google" lets Google confirm who you are and tell the website. You never type your Google password into the website; you are sent to Google, you approve, and Google sends you back with a proof. OAuth is the protocol for granting such access, and OpenID Connect is the layer on top that tells the website who the user is. Afterwards, the website's own job is to decide what each signed-in person is allowed to do.

Words to know

  • OAuth 2.0: a standard for giving an app limited access to an account without sharing the password.
  • OpenID Connect (OIDC): a layer on OAuth that provides the user's identity as an ID token.
  • Identity provider (IdP): the service that signs the user in, such as Google or Keycloak.
  • Authorization: deciding what a signed-in user may do.

OAuth 2.0 and OpenID Connect

OAuth 2.0 (RFC 6749) is about delegated authorisation: a user lets your application access something (their calendar, repositories) at another service with limited scopes, via an access token, without giving your app their password. OpenID Connect adds authentication: an ID token (a JWT) that says who the user is (sub, email, name), plus a userinfo endpoint. For "log in with X", you use OIDC (people say OAuth loosely).

Roles in the flow:

  • User (resource owner).
  • Client: your web app or API (it must be registered with the provider, giving you a client id and secret and registered redirect URIs).
  • Authorization server / identity provider: Google, Microsoft, GitHub (OAuth only), Keycloak, Auth0, Okta.
  • Resource server: the API that accepts access tokens.

Benefits: users avoid yet another password, you avoid storing and securing passwords, you get verified emails and MFA from the provider, and sign-up is a single click (important for conversion on phones). Costs: dependence on the provider, privacy considerations, and care with account linking.

The authorization code flow with PKCE

For web apps and single-page apps, the recommended flow is the authorization code flow with PKCE (Proof Key for Code Exchange, RFC 7636), and current security guidance (the OAuth 2.0 Security Best Current Practice, RFC 9700) says to use it for all clients. The implicit flow and the password grant are obsolete.

  1. The user clicks "Sign in with Google". Your server creates random state (CSRF protection), nonce (replay protection for the ID token) and a PKCE code_verifier (random), and its hash, the code_challenge. It stores these in the user's session.
  2. Your server redirects the browser to the provider's authorization endpoint:
https://accounts.google.com/o/oauth2/v2/auth
  ?client_id=...
  &redirect_uri=https://app.example.com/auth/callback
  &response_type=code
  &scope=openid%20email%20profile
  &state=xyz&nonce=abc
  &code_challenge=...&code_challenge_method=S256
  1. The user signs in at the provider and approves the requested scopes.
  2. The provider redirects back to your redirect_uri with ?code=...&state=xyz.
  3. Your server checks state matches, then calls the provider's token endpoint directly (server to server) sending the code, client_id, client_secret (for confidential clients), redirect_uri and the code_verifier.
  4. The provider returns an ID token, an access token and often a refresh token.
  5. Your server validates the ID token (signature using the provider's published keys, iss, aud equal to your client id, exp, and the nonce), reads sub and email, finds or creates the local user, and starts your own session (or issues your own tokens).

Why a code and not tokens in the redirect? The authorization code is useless without the client secret and PKCE verifier, so interception of the redirect (browser history, logs, malicious apps) does not give an attacker tokens. Never use a token that arrives in a URL fragment, and never skip state.

Using a library

Implementing the flow by hand is error-prone. Use a well-maintained, certified OpenID library:

  • openid-client (a certified OIDC client for Node.js): discovery, PKCE, token validation.
  • Passport with passport-google-oauth20 or passport-openidconnect: a familiar strategy-based middleware.
  • Libraries and frameworks with built-in auth: Auth.js, better-auth, Lucia-style session helpers.
  • Or a hosted identity provider's SDK (Auth0, Clerk, Cognito, Firebase Auth, Keycloak adapters) which can take over the whole login UI.

A sketch with openid-client (check the library's documentation for the current API, which changes between major versions):

import * as client from "openid-client";

const config = await client.discovery(new URL("https://accounts.google.com"), process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET);

app.get("/auth/google", async (req, res) => {
  const codeVerifier = client.randomPKCECodeVerifier();
  const state = client.randomState();
  const nonce = client.randomNonce();
  req.session.oauth = { codeVerifier, state, nonce };
  const url = client.buildAuthorizationUrl(config, {
    redirect_uri: `${process.env.PUBLIC_URL}/auth/callback`,
    scope: "openid email profile",
    code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
    code_challenge_method: "S256",
    state, nonce,
  });
  res.redirect(url.href);
});

app.get("/auth/callback", async (req, res) => {
  const { codeVerifier, state, nonce } = req.session.oauth ?? {};
  const currentUrl = new URL(req.originalUrl, process.env.PUBLIC_URL);
  const tokens = await client.authorizationCodeGrant(config, currentUrl, {
    pkceCodeVerifier: codeVerifier, expectedState: state, expectedNonce: nonce,    // the library validates all of these
  });
  const claims = tokens.claims();                        // validated ID token claims: sub, email, email_verified, name
  if (!claims.email_verified) return res.status(403).send("Email not verified.");
  const user = await users.findOrCreateFromProvider("google", claims.sub, claims.email, claims.name);
  req.session.regenerate(() => { req.session.userId = user.id; res.redirect("/"); });
});

Rules for a safe callback:

  • Always verify state and, with OIDC, the nonce; use PKCE even for confidential clients.
  • Register exact redirect URIs with the provider (no wildcards); never accept a redirect_uri from user input.
  • Identify users by the provider's stable sub claim (with the issuer), not by email alone; emails can change or be reused. Trust an email only when email_verified is true.
  • Account linking: if a local account with that email already exists, link only after proving ownership (for example, the user is signed in with the other method, or confirms by email), or you create an account-takeover hole.
  • Keep the client_secret in the environment or secret manager, never in front-end code. A pure browser app (SPA) cannot keep secrets: use PKCE with a public client, or a "backend for frontend" that holds secrets and tokens and gives the browser only a session cookie.
  • Request the minimum scopes. Store refresh tokens only if you need offline access, encrypted at rest.
  • Handle errors on the callback (?error=access_denied) with a friendly message and a way back.

CSRF, CORS and other protections

  • With cookie-based sessions, protect state-changing requests against CSRF: SameSite=Lax or Strict cookies plus anti-CSRF tokens (the double-submit or synchroniser token pattern, libraries such as csrf-csrf) and checking the Origin header.
  • Configure CORS with an allow-list and credentials: true only when needed (the CORS lesson).
  • Set security headers with Helmet, force HTTPS, and add rate limits on /auth/* routes.
  • Logout should destroy the session and, where the provider supports it, redirect to its logout endpoint (RP-initiated logout).
  • Log authentication events; never log tokens, codes or secrets.

Testing protected routes

import test from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { app } from "../src/app.js";

test("anonymous users get 401", async () => {
  const res = await request(app).get("/api/orders");
  assert.equal(res.status, 401);
});

test("a user cannot read another user's order", async () => {
  const agent = request.agent(app);                         // keeps cookies across requests
  await agent.post("/test/login").send({ userId: 1 });       // a test-only helper that creates a session
  const res = await agent.get("/api/orders/9001");           // order 9001 belongs to user 2
  assert.equal(res.status, 404);
});

test("only admins reach /api/admin", async () => {
  const agent = request.agent(app);
  await agent.post("/test/login").send({ userId: 1, role: "user" });
  assert.equal((await agent.get("/api/admin/stats")).status, 403);
});

Test the negative cases at least as much as the positive: unauthenticated, wrong role, wrong owner, expired or tampered token, a missing state. For the OAuth callback itself, test against a local provider (Keycloak in Docker) or mock the provider's endpoints.

Common mistakes

  • Identifying users by email only and linking accounts without verification.
  • Skipping state, nonce or PKCE, or accepting arbitrary redirect_uri values.
  • Putting the client secret in front-end code.
  • Authenticating but not authorising: any logged-in user can read any object.
  • Trusting role claims or isAdmin flags sent by the client.
  • Protecting only the front-end routes.
  • Returning 403 for other users' objects, revealing that they exist (404 is often better).
  • Rolling your own OAuth client instead of a certified library.

Try it yourself

  1. Register an OAuth client in Google Cloud (or run Keycloak locally) and implement login with openid-client or Passport, with state, nonce and PKCE.
  2. Map the provider's sub to a local user; refuse unverified emails.
  3. Protect /api/orders with requireAuth, /api/admin with requireRole("admin"), and return the right 401 and 403 responses.
  4. Add the ownership check to GET /api/orders/:id in the SQL query and write a test proving user A cannot read user B's order.
  5. Try tampering with the state parameter on the callback and confirm the login fails.

Check yourself

What is the difference between OAuth 2.0 and OpenID Connect?

OAuth 2.0 delegates authorisation (access tokens for APIs); OpenID Connect builds on it to authenticate users, adding an ID token that states who the user is.

What are state and PKCE for in the authorization code flow?

state binds the callback to the original request to prevent CSRF; PKCE ties the code exchange to the client that started the flow so an intercepted code is useless to an attacker.

What is the difference between 401 and 403?

401 means the request is not authenticated (missing or invalid credentials); 403 means the caller is authenticated but not permitted to perform the action.

What is object-level authorisation and why does it matter?

Checking that the signed-in user may access the specific object requested (for example their own order); skipping it lets users read or change others' data by guessing ids, the most common API vulnerability.

Interview questions

Walk through "Sign in with Google" in a web app.

The server redirects to Google's authorization endpoint with client id, redirect URI, scopes, state, nonce and a PKCE challenge; the user signs in and consents; Google redirects back with a code; the server verifies state, exchanges the code (with the PKCE verifier and client secret) for tokens, validates the ID token, finds or creates the local user by sub, and starts a session.

How do you secure the routes of an Express API?

Apply authentication middleware (sessions or token verification) by default to routers, add role or permission checks, enforce object-level ownership in queries and services, validate input, use CSRF and CORS protections, rate limits and HTTPS, return correct 401 and 403 responses and test the negative cases.

Why identify users by sub rather than email?

sub is the provider's stable unique identifier for the user; emails can change, be reassigned, or be unverified, so using them as identity can allow account takeover.

Summary

  • OIDC "Sign in with X" uses the authorization code flow with PKCE, state and nonce; use a certified library and exact redirect URIs.
  • Identify users by issuer and sub, trust only verified emails, link accounts carefully and keep secrets on the server.
  • Protect routes by default: authentication middleware, role or permission checks, and above all object-level ownership checks in queries and services.
  • Add CSRF, CORS, rate limiting and HTTPS, and test the unauthorised and cross-user cases.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.