Lesson 8 of 8 · 15 min · Authentication
OAuth and OpenID Connect login, and protecting routes
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.
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-oauth20orpassport-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
stateand, with OIDC, thenonce; use PKCE even for confidential clients. - Register exact redirect URIs with the provider (no wildcards); never accept a
redirect_urifrom user input. - Identify users by the provider's stable
subclaim (with the issuer), not by email alone; emails can change or be reused. Trust an email only whenemail_verifiedis 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_secretin 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.
After login: protect your routes
Authentication establishes who; your API must still decide what they can do. Layer the checks:
// 1. Authentication middleware: is there a valid session or token?
export function requireAuth(req, res, next) {
if (!req.session?.userId) return next(new UnauthorizedError());
next();
}
// load the user once and attach it
export async function loadUser(req, res, next) {
if (req.session?.userId) req.user = await users.findById(req.session.userId);
next();
}
// 2. Authorisation by role or permission
export const requireRole = (...roles) => (req, res, next) => {
if (!req.user) return next(new UnauthorizedError());
if (!roles.includes(req.user.role)) return next(new ForbiddenError());
next();
};
// usage
app.use("/api", loadUser);
app.use("/api/orders", requireAuth, ordersRouter);
app.use("/api/admin", requireAuth, requireRole("admin"), adminRouter);
Use 401 Unauthorized when the caller is not authenticated and 403 Forbidden when they are authenticated but not allowed. Apply authentication to a whole router with router.use(requireAuth) so a new route is protected by default (deny by default), and open only the few public routes explicitly.
Object-level authorisation (the one that matters most)
The most common serious API flaw is Broken Object Level Authorization (OWASP API Security Top 10, also called IDOR): a logged-in user changes an id in the URL and reads or edits someone else's data.
router.get("/:id", async (req, res) => {
const order = await orders.get(Number(req.params.id));
if (order.customerId !== req.user.id && req.user.role !== "admin") {
throw new NotFoundError("Order", req.params.id); // 404 (not 403) avoids revealing that it exists
}
res.json(order);
});
Better: build the check into the query so other users' rows can never be returned: SELECT ... FROM orders WHERE id = $1 AND customer_id = $2. Put these rules in the service layer (not only in routes), write them once, and test them: user A must not read, update or delete user B's resources, for every endpoint. Related risks: mass assignment (validate and allow-list fields), function-level authorisation (admin endpoints reachable by normal users), and excessive data exposure (return only the fields a role should see).
Roles, permissions and policies
- Start with simple roles (
user,admin) stored in the database (not trusted from the client). - When rules grow, move to permissions (
orders:read,orders:refund) or policy-based checks (a functioncan(user, "refund", order)); libraries such as CASL or Casbin help. Keep the policy in one place. - Tokens: if you use JWTs, verify the signature,
exp,iss,audand checkscopeorroleclaims; for sensitive actions re-check the database. - Re-authentication for sensitive actions (change email, payments), MFA for admin accounts, and audit logs of who did what.
Front end routes
A React route guard (the earlier routing lesson) only improves the user experience. The API must enforce every rule, since anyone can call it directly.
CSRF, CORS and other protections
- With cookie-based sessions, protect state-changing requests against CSRF:
SameSite=LaxorStrictcookies plus anti-CSRF tokens (the double-submit or synchroniser token pattern, libraries such ascsrf-csrf) and checking theOriginheader. - Configure CORS with an allow-list and
credentials: trueonly 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,nonceor PKCE, or accepting arbitraryredirect_urivalues. - Putting the client secret in front-end code.
- Authenticating but not authorising: any logged-in user can read any object.
- Trusting role claims or
isAdminflags 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
- Register an OAuth client in Google Cloud (or run Keycloak locally) and implement login with
openid-clientor Passport, withstate,nonceand PKCE. - Map the provider's
subto a local user; refuse unverified emails. - Protect
/api/orderswithrequireAuth,/api/adminwithrequireRole("admin"), and return the right 401 and 403 responses. - Add the ownership check to
GET /api/orders/:idin the SQL query and write a test proving user A cannot read user B's order. - Try tampering with the
stateparameter 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,
stateandnonce; 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
- OpenID Connect Core 1.0: the specification.
- RFC 6749: OAuth 2.0 Authorization Framework and RFC 7636: PKCE: the base standards.
- OWASP API Security Top 10: broken object-level authorisation and friends.
- OWASP: Authorization Cheat Sheet: deny by default, least privilege and testing.
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.