Before your interview: sessions vs. JWT, OAuth 2.0 and OpenID Connect
Where a login actually lives after the password check: server-side sessions, JWTs and their real pitfalls, where to store tokens in the browser, and why OAuth is not a login protocol. Authorization code with PKCE, state and nonce, and the follow-up questions that come with them.
Checking a password takes one line of code. The hard part is everything after it: how the server remembers, on the next hundred requests, that this browser belongs to a user who logged in. That is what this interview topic is about, and the questions come in a predictable chain: “session or JWT?”, then “where do you store the token?”, then “how do you log someone out?”, then “how does ‘Sign in with Google’ work?”. Each step has a popular answer that is half wrong.
The thread through all of it: a session or a token is a bearer credential. Whoever holds it is the user, until it expires or the server refuses it. Every design choice in this part is a trade between how easily you can refuse it (revocation), how far it travels (exposure) and how much state the server keeps (cost).
This is part 3 of the series. Part 2 covered XSS and CSRF; both come back here, because where you store a credential decides which of the two can steal or abuse it.
TL;DR#
- A server-side session is a random ID pointing to state on the server. Logging out deletes the state. A JWT carries its state inside, signed; the server can’t “delete” it, only wait for it to expire or keep a denylist, which is server-side state again.
- JWT failures are verification failures: accepting
alg: none, letting the token choose the algorithm (RS256 → HS256 confusion), fetching keys from a URL in the header, and not checkingexp,audandiss. - There is no safe place for a token in the browser, only trade-offs.
localStorageis readable by any XSS; anHttpOnlycookie can’t be read by script but brings CSRF back. For high-value apps, a backend-for-frontend keeps tokens off the browser entirely. - OAuth 2.0 delegates access; it does not tell you who the user is. OpenID Connect adds the ID token for that. Using an OAuth access token as proof of login is a classic vulnerability.
- Authorization code + PKCE is the flow for everything now, including single-page and mobile apps. The implicit flow is deprecated.
stateprotects the callback against CSRF,noncebinds the ID token to the login attempt.
The mechanism#
Server-side sessions#
After login, the server generates a long random session ID (128 bits of randomness or more, from a cryptographically secure generator), stores the session data (user ID, roles, expiry) in memory, a database or Redis, and sends the ID in a cookie. Every request brings the cookie back; the server looks the ID up.
The properties follow directly. Revocation is instant: delete the row, and the cookie is worthless. “Log out all devices”, “kill this session” and “the admin disabled this account” all work immediately. The cost is a lookup per request and a shared store when you run more than one server. That is a real cost, but a small one: a Redis lookup is well under a millisecond.
The known session bugs are about the ID’s lifecycle:
- Session fixation: the server keeps the same session ID before and after login. An attacker who planted a known ID in the victim’s browser (through a sibling subdomain setting a cookie, or an ID accepted from the URL) is logged in once the victim logs in. Fix: issue a new ID at every privilege change, login included.
- No expiry: sessions need an idle timeout and an absolute lifetime, enforced on the server, not only in the cookie’s
Max-Age. - Weak cookie attributes:
Secure,HttpOnly,SameSite, and a__Host-prefix, as covered in parts 1 and 2.
JWTs#
A JSON Web Token (JWT) is three base64url-encoded parts joined with dots: a header ({"alg":"RS256","kid":"key-2026"}), a payload of claims (sub, exp, aud, iss, roles), and a signature over the first two. The server that receives it checks the signature and the claims, and needs no database to know who the user is. That is the whole point, and also the whole problem.
Two clarifications that interviewers check:
- A JWT is signed, not encrypted. Anyone holding it can read the payload; paste one into a decoder and see. (Encrypted JWTs, JWE, exist but are rare.) Never put secrets or personal data in claims you wouldn’t show the user.
- Stateless means unrevocable. If a token is valid for an hour, a stolen token is valid for an hour. The standard answers are short access-token lifetimes (5–15 minutes) with a refresh token to get new ones, refresh-token rotation (each use returns a new refresh token and invalidates the old one, so reuse of a stolen one is detectable), and a denylist of token IDs (
jti) for emergencies. The denylist is a lookup per request, which is what the session design had.
The real-world JWT vulnerabilities are all in verification:
| Bug | What happens | Fix |
|---|---|---|
alg: none accepted | The attacker removes the signature and sets "alg":"none"; some libraries accepted it as valid | Pin the expected algorithm in the verifier; never read it from the token |
| Algorithm confusion | Server expects RS256 (asymmetric); attacker sends HS256 signed with the server’s public key as the HMAC secret; a library that picks the algorithm from the header verifies it | Same: one algorithm per key, configured on the server |
jku / x5u / embedded jwk | The header points to a key set at a URL, or embeds a key; the server trusts it and verifies with the attacker’s key | Keys come only from your configuration or a pinned JWKS URL |
kid injection | The key ID is used in a file path or SQL query to look up the key | Treat kid as untrusted input: look it up in a fixed map |
| Missing claim checks | exp not checked, or a token issued for service A (aud) accepted by service B | Validate exp, nbf, iss and aud on every token |
| Weak HMAC secret | secret123 is brute-forced offline from a single token | 256-bit random secret, or asymmetric keys |
The pattern behind the table is that the token is attacker-controlled input until verified, and several fields in it tell the verifier how to verify. A good library, configured with one expected algorithm and a fixed key, removes the first four rows.
Where to store it in the browser#
This question comes up in every interview that mentions JWTs, and the honest answer is a trade-off table:
| Storage | XSS can… | CSRF? | Notes |
|---|---|---|---|
localStorage / sessionStorage | Read the token and send it anywhere; it keeps working after the user closes the tab | No (the token is added by script) | Exfiltration is the problem: the attacker uses it from their own machine |
| JavaScript memory only | Use it while the page is open, and with some effort read it | No | Lost on reload; usually paired with a refresh token in a cookie |
HttpOnly cookie | Use the session from the victim’s browser, but not read it | Yes, so SameSite and CSRF defenses apply | The session-cookie model; the token never touches script |
| Backend-for-frontend (BFF) | Use the session from the browser, nothing more | Yes, same as above | Tokens stay on a server-side component; the browser holds only a session cookie |
The distinction that earns points: with XSS the attacker can act as the user in every row. What changes is whether they can also steal a credential and keep using it later, from anywhere. HttpOnly cookies and the BFF pattern prevent the theft. That is why the IETF’s guidance for browser-based OAuth apps recommends a BFF for sensitive applications.
OAuth 2.0: delegation, not login#
OAuth 2.0 solves a specific problem: a user wants to let one application (the client, say a photo-printing service) access their data on another (the resource server, say a photo library) without giving the client their password. The authorization server asks the user to consent, then gives the client an access token limited to certain scopes (photos.read).
The flow everyone should be able to draw is the authorization code flow with PKCE:
1. Client → browser → AS /authorize?response_type=code&client_id=…&redirect_uri=…
&scope=…&state=RANDOM&code_challenge=SHA256(verifier)
2. User logs in at the AS and consents
3. AS → browser → client redirect_uri?code=ONE_TIME_CODE&state=RANDOM
4. Client checks state, then back-channel to AS:
POST /token code=…&code_verifier=verifier (&client secret)
5. AS → client access token (+ refresh token, + ID token with OIDC)
Each parameter exists because of an attack:
state: a random value tied to the user’s browser session, checked at step 4. Without it, an attacker can feed their own authorization code into the victim’s callback (CSRF on the callback), linking the victim’s account to the attacker’s identity.- PKCE (Proof Key for Code Exchange, RFC 7636): the client invents a secret
code_verifier, sends only its hash at step 1, and must present the verifier at step 4. A code intercepted at step 3 (by a malicious app registered for the same mobile URL scheme, or leaked through logs or aRefererheader) is useless without it. Originally for mobile apps, now recommended for every client. - Exact
redirect_urimatching: if the authorization server accepts any URL that starts with the registered one, or any path on the domain, an open redirect on the client’s site sends codes or tokens to the attacker. - The back channel at step 4: the token never passes through the browser’s URL, history or
Referer.
The implicit flow (tokens returned directly in the redirect URL fragment) was the old answer for single-page apps. The OAuth 2.0 Security Best Current Practice (RFC 9700, published in 2025) says not to use it, and not to use the resource owner password grant either. OAuth 2.1, still a draft, folds these rules into the core spec.
OpenID Connect: who the user is#
OAuth gives the client an access token meant for an API. It says nothing reliable to the client about who logged in. OpenID Connect (OIDC) is a thin layer on top that adds an ID token: a signed JWT, issued to the client (aud = the client’s ID), stating who the user is (sub, iss), when they authenticated, and how.
The classic bug when this is missing: an app implements “Sign in with X” by taking any access token, calling X’s profile API, and logging in whoever the profile says. A malicious app that collected users’ access tokens for its own purposes can now replay them into the vulnerable app and log in as those users. The token was never issued for that app, and nothing checked. With OIDC, the client verifies that the ID token’s aud is its own client ID.
The nonce is the ID-token counterpart of state: a random value the client sends in step 1, which the authorization server copies into the ID token. The client checks it, which binds the token to this login attempt and stops replay of an ID token captured elsewhere.
The questions, and what they really want to hear#
“Sessions or JWTs: which would you use, and why?”#
What it tests: whether you know what “stateless” costs.
30-second answer: “For a typical web app with its own back end, server-side sessions in an HttpOnly, SameSite cookie: revocation is instant and the token never touches JavaScript. JWTs make sense when separate services must verify identity without calling a central store, for example between microservices or for API access tokens from an identity provider. Then I keep them short-lived, use refresh-token rotation, and pin the algorithm and keys in verification.”
Deeper: “stateless” is mostly a myth in production. You need logout, account disabling and “sign out everywhere”, and each one brings state back (a denylist or short lifetimes with a stateful refresh token). Name the cost honestly: sessions need a shared store; JWTs need key management, rotation and careful verification.
Follow-ups to expect:
- Junior: “Is the data in a JWT encrypted?” “What’s in the three parts?”
- Mid: “How do you log a user out if you use JWTs?” “What’s session fixation?”
- Senior: “Design token handling for a mobile app, a single-page app and twenty microservices behind one identity provider.”
“What can go wrong with JWT validation?”#
What it tests: whether you’ve seen the real bugs, not just the format.
30-second answer: “Most bugs come from letting the token tell the verifier how to verify it: accepting alg: none, algorithm confusion between RS256 and HS256, trusting a key URL or an embedded key from the header, and using kid unsafely. Then missing claim checks, especially aud, so a token for one service works on another. The fix is a maintained library configured with one expected algorithm and fixed keys, and checking exp, iss and aud every time.”
Follow-ups: “Explain algorithm confusion step by step.” “How would you test a JWT implementation?” (Change the algorithm, strip the signature, edit claims, try a token from another environment, brute-force a weak HMAC secret offline with hashcat.)
“Where should a single-page app store its tokens?”#
What it tests: that you see the trade-off instead of reciting a rule.
30-second answer: “Nowhere in the browser is safe against XSS; the question is whether XSS can steal the token or only use it. localStorage lets it steal; an HttpOnly cookie doesn’t, but then I need CSRF protection. For sensitive apps I’d use a backend-for-frontend: the browser has only a session cookie, and the tokens stay on the server.”
Deeper: mention in-memory storage with a refresh token in an HttpOnly cookie as a middle ground, and that preventing XSS (part 2) matters more than the storage choice.
“Explain OAuth 2.0. Is it an authentication protocol?”#
What it tests: the authentication / delegation distinction.
30-second answer: “No, it’s for delegated authorization: a user lets an application access an API on their behalf, with limited scopes, without sharing a password. The client gets an access token meant for the API, not for itself. Authentication on top of OAuth is OpenID Connect, which adds an ID token addressed to the client that says who the user is.”
Follow-ups: “What goes wrong if an app uses an access token as proof of login?” (Token substitution, as above.) “What’s the difference between scopes and roles?”
“Walk me through the authorization code flow. Why PKCE? What are state and nonce for?”#
What it tests: whether you know each parameter by the attack it stops.
30-second answer: “The client redirects the user to the authorization server with its client ID, redirect URI, scopes, a random state and a PKCE code challenge. After consent, the server redirects back with a one-time code. The client checks state, then exchanges the code plus the PKCE verifier for tokens on a back channel. state stops CSRF on the callback, PKCE makes an intercepted code useless, and with OIDC the nonce ties the ID token to this login.”
Deeper: why the implicit flow is deprecated (tokens in URLs leak through history, logs and Referer, and nothing binds them to the client), why redirect URIs need exact matching, and why public clients (browsers, mobile apps) can’t keep a client secret, which is what PKCE compensates for.
Follow-ups:
- Senior: “How would you review an OAuth integration in a pentest?” (Redirect URI manipulation, missing or static
state, code reuse, PKCE downgrade by omitting the challenge, scope escalation, token leakage throughReferer, account linking flows.)
Answers that cost points#
- “JWTs are secure because they’re encrypted.” They’re signed. The payload is readable by anyone who has the token.
- “JWTs are stateless, so they scale better.” Until you need logout or revocation; then you add state back. Sessions in Redis scale fine.
- “Store the token in
localStorage, it’s not vulnerable to CSRF.” True, and it hands the token to any XSS. Name both sides. - “OAuth is how you log users in.” OAuth delegates access; OIDC authenticates.
- “PKCE is only for mobile apps.” Current best practice is PKCE for all clients, confidential ones included.
- "
stateis optional." It is the CSRF protection for the callback. PKCE also prevents that particular attack when the authorization server enforces it, but a reviewer will still ask whystateis missing. - “Refresh tokens are just long-lived access tokens.” They go only to the authorization server, never to APIs, and should be rotated and bound to the client.
The same topic in different interviews#
- Pentester: testing JWTs (algorithm and signature tampering, claim editing, weak secrets, cross-environment tokens), session handling (fixation, logout that doesn’t invalidate the server-side session, missing timeouts), and OAuth flows (redirect URI tricks,
statehandling, code reuse, account linking). - AppSec: choosing the model per application, library configuration for JWT verification, cookie attributes, BFF vs. browser-held tokens, and code review of the callback handler.
- Security engineer: identity provider configuration, key rotation and JWKS publishing, token lifetimes and refresh policy, session revocation across services, and service-to-service authentication.
Practice#
- The free PortSwigger Web Security Academy chapters on JWT attacks and OAuth 2.0 authentication vulnerabilities. The OAuth labs reproduce most of the bugs above.
- This site’s JWT inspector decodes a token in the browser, without sending it anywhere, flags risky headers and claims (
alg: none,jku, a suspiciouskid, noaudorexp), and tests HMAC tokens against well-known default secrets. - Log in to any site with “Sign in with Google” or GitHub with the browser’s Network tab open, and find the
/authorizerequest, thestateandcode_challengeparameters, and the callback with the code.
Test yourself#
An API verifies RS256 tokens with a library call like verify(token, publicKey) and no algorithm parameter. What is the attack, and what is the one-line fix?
Answer
Algorithm confusion. If the library takes the algorithm from the token header, an attacker sets "alg":"HS256" and signs the token with HMAC, using the server’s public key (which is public) as the HMAC secret. The library sees HS256, uses the “key” it was given as the secret, and the signature checks out. The fix is to pass the expected algorithm explicitly, for example verify(token, publicKey, {algorithms: ["RS256"]}), so the token’s header can’t change how it’s verified. Modern library versions often refuse this combination by default, but a reviewer should still see the algorithm pinned.
A user reports a stolen laptop. The app uses JWT access tokens valid for 24 hours and no refresh tokens. What can you do right now, and what would you change?
Answer
Right now, very little without new state: the tokens are valid until they expire. Options are to add the token IDs (jti) or the user’s ID with a “tokens issued before” timestamp to a denylist checked on every request, or to rotate the signing key, which logs out every user. Long term: short-lived access tokens (minutes), refresh tokens that are stored server-side, rotated on each use and revocable per device, so “revoke this device” deletes one refresh token and the access token dies within minutes. Or use server-side sessions, where revocation is a delete.
A shopping site’s “Sign in with SocialNet” takes the OAuth access token from the browser, calls SocialNet’s /me endpoint, and logs in the user with the returned ID. Why is this vulnerable, and how does OIDC fix it?
Answer
The access token was issued for SocialNet’s API, not for the shopping site, and nothing checks which app it was issued to. Any other app that users have authorized with SocialNet (say, a quiz game) collects valid access tokens; its owner can send a victim’s token to the shopping site and be logged in as the victim. With OIDC, the shopping site receives an ID token whose aud claim is the shopping site’s own client ID, signed by SocialNet; a token issued to the quiz game has a different aud and is rejected. The site must also check iss, exp and the nonce.
Further reading#
- RFC 9700: OAuth 2.0 Security Best Current Practice, the current rules in one document.
- RFC 7636 (PKCE) and RFC 8725 (JSON Web Token Best Current Practices).
- OpenID Connect Core 1.0: ID token validation rules, section 3.1.3.7.
- IETF draft OAuth 2.0 for Browser-Based Applications: the BFF pattern and the trade-offs of token storage.
- OWASP Session Management Cheat Sheet and JSON Web Token for Java Cheat Sheet (the advice applies beyond Java).