OAuth and JWT interview questions: flows, tokens and security
OAuth interview questions check whether you understand delegated authorization: who the client, resource owner, authorization server and resource server are, which grant fits which app, and how tokens are issued, validated, refreshed and revoked. Most interviews pair OAuth 2.0 with OpenID Connect for login and with JWTs as the token format, then ask about sessions versus tokens and the security mistakes that lead to account takeover. The authorization code flow with PKCE is the one flow you must be able to draw from memory.
By Evin JohnPublished 10 min read
Where OAuth questions come from
Identity questions appear in backend, full stack, mobile, platform and security interviews, usually in one of three forms. Concept questions ask you to define the roles and explain a flow. Design questions ask you to add "Sign in with Google" or protect a set of microservices. Review questions show a token, a redirect or a snippet of code and ask what is wrong. Interviewers listen for precise terms: an access token is not an ID token, authentication is not authorization, and a signed JWT is readable by anyone who holds it.
Fundamentals: roles, grants and scopes
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Authentication versus authorization? | Basics | Authentication proves who someone is; authorization decides what they may do. OAuth 2.0 alone is an authorization framework, which is why OpenID Connect exists. |
| Name the four OAuth roles. | Vocabulary | Resource owner (the user), client (the app asking for access), authorization server (issues tokens) and resource server (the API that accepts them). |
| What problem did OAuth solve? | Motivation | Letting an app act on a user's data in another service without the user handing over their password, with limited scope and the ability to revoke access. |
| What is a scope? | Consent | A named permission the client asks for, such as read access to a calendar. The user consents to scopes, and the token carries the ones granted, which may be fewer than requested. |
| Confidential versus public clients? | Client types | Confidential clients (server-side apps) can keep a secret. Public clients (single-page apps, mobile and desktop apps) cannot, because anyone can read their code, so they rely on PKCE instead of a secret. |
| Which grant would you use for each kind of app? | Choosing flows | Authorization code with PKCE for user-facing web, mobile and SPA clients. Client credentials for a backend calling another backend with no user. Device authorization for TVs and CLIs without a browser. Refresh token grant to renew access. |
| Why are the implicit and password grants discouraged? | Current practice | Implicit returns tokens in the URL fragment, where they leak through history and referrers, with no way to bind them to the client. The password grant teaches users to type passwords into third-party apps. The OAuth security best current practice (RFC 9700) advises against both, and the OAuth 2.1 draft drops them. |
| What is the redirect URI for, and how must it be checked? | Security | It is where the authorization server sends the code. The server must compare it exactly against a pre-registered value; loose matching lets attackers steal codes through open redirects. |
What is the state parameter? | CSRF defense | A random value the client stores before redirecting and checks when the user comes back, so an attacker cannot inject their own authorization response into the victim's session. |
The authorization code flow with PKCE
- Create a verifier and challengeThe client generates a random
code_verifierand derivescode_challengeas the base64url SHA-256 hash of it. - Redirect to the authorization serverWith
response_type=code, the client id, the exact redirect URI, scopes, astatevalue and the code challenge withcode_challenge_method=S256. - User signs in and consentsThe authorization server authenticates the user (password, passkey, MFA) and shows the requested scopes.
- Code comes backThe browser is redirected to the client's redirect URI with a short-lived, single-use authorization code and the same
state. - Exchange the codeThe client posts the code and the original
code_verifierto the token endpoint over TLS. The server hashes the verifier and checks it against the stored challenge. - Receive tokensAn access token for the API, optionally a refresh token, and with OpenID Connect an ID token describing the user.
- What attack does PKCE stop? Authorization code interception: a malicious app or a leaked log gets the code, but it cannot exchange it without the verifier, which never left the legitimate client.
- Why use S256 and not the plain method? With plain, the challenge equals the verifier, so anyone who saw the authorization request can redeem the code. S256 sends only a hash.
- Should confidential clients use PKCE too? Yes. Current guidance recommends PKCE for all clients using the code flow, since it also protects against code injection.
- Why is the code exchanged on a back channel? The front channel (browser redirects) is visible to the user agent, extensions and logs. Tokens travel only in the direct, TLS-protected request from client to token endpoint.
import { createHash, randomBytes } from "node:crypto";
const base64url = (buf) => buf.toString("base64url");
function challengeFor(verifier) {
return base64url(createHash("sha256").update(verifier).digest());
}
// A fresh verifier: 32 random bytes give a 43-character base64url string.
const verifier = base64url(randomBytes(32));
console.log(verifier.length, challengeFor(verifier).length); // 43 43
// The RFC 7636 example values.
const rfcVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
console.log(challengeFor(rfcVerifier));
// E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMTokens: access, refresh and ID
| Token | Audience | Purpose | Typical lifetime |
|---|---|---|---|
| Access token | The resource server (API) | Authorizes API calls for the granted scopes. Can be a JWT or an opaque string. | Short: minutes to an hour |
| Refresh token | The authorization server only | Gets new access tokens without the user signing in again. Never sent to APIs. | Longer: hours to weeks, often sliding with rotation |
| ID token (OIDC) | The client | Tells the client who signed in and how. Always a JWT. Not for calling APIs. | Short; used once at login |
- JWT access token or opaque token? A JWT can be validated locally by any API with the public key, with no network call, but it cannot be revoked before it expires unless you add a deny list. An opaque token must be checked with the authorization server (token introspection, RFC 7662), which allows instant revocation at the cost of a call or a cache.
- What is refresh token rotation? Each time a refresh token is used, the server issues a new one and invalidates the old. If an old one is ever presented again, the server treats it as theft and revokes the whole token family.
- How do you log a user out everywhere? Revoke their refresh tokens and sessions at the authorization server, keep access tokens short so they die quickly, and use back-channel logout or a revocation list where minutes matter.
- What is a sender-constrained token? A token bound to a key the client holds, through mutual TLS or DPoP, so a stolen token is useless without that key. Plain bearer tokens work for whoever holds them.
- Why must an API check the audience? A token issued for API A must not be accepted by API B. Without an
audcheck, any token from the same issuer works everywhere, so one compromised service can call the others.
JWT structure and validation
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the three parts of a JWT? | Structure | A base64url-encoded header (algorithm, key id), payload (claims) and signature, joined by dots. Anyone can decode the first two parts. |
| Is a JWT encrypted? | Common myth | A normal signed JWT (JWS) is only encoded, not encrypted, so never put secrets in it. Encrypted tokens (JWE) exist but are less common. |
| Which registered claims matter? | Claims | iss (issuer), sub (subject), aud (audience), exp (expiry), nbf (not before), iat (issued at) and jti (unique id, useful for revocation lists). |
| HS256 versus RS256 or ES256? | Algorithms | HS256 uses one shared secret to sign and verify, so every verifier could also mint tokens. RS256 and ES256 sign with a private key and verify with a public key, which suits many independent APIs. |
What is the alg: none attack? | Classic flaw | Some old libraries trusted the header's algorithm, so a token with no signature passed. Always pin the expected algorithms on the server side. |
| What is algorithm confusion? | Classic flaw | A server expecting RS256 is fed an HS256 token signed with the public key used as an HMAC secret. Pinning the algorithm per key prevents it. |
| How does key rotation work with JWKS? | Operations | The issuer publishes public keys at a JWKS endpoint, each with a kid. Tokens name their kid; verifiers cache the key set and refetch when they see an unknown id, so old and new keys overlap during rotation. |
| How do you handle clock skew? | Practical | Allow a small leeway, often seconds to a couple of minutes, when checking exp and nbf, and keep server clocks synced. |
import { createHmac, timingSafeEqual } from "node:crypto";
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const sign = (data, secret) => createHmac("sha256", secret).update(data).digest("base64url");
function issue(claims, secret) {
const head = b64({ alg: "HS256", typ: "JWT" });
const body = b64(claims);
return [head, body, sign(head + "." + body, secret)].join(".");
}
function verify(token, secret, { iss, aud, now = Math.floor(Date.now() / 1000) }) {
const [head, body, sig] = token.split(".");
const header = JSON.parse(Buffer.from(head, "base64url"));
if (header.alg !== "HS256") throw new Error("unexpected alg"); // never trust the header
const expected = Buffer.from(sign(head + "." + body, secret));
const given = Buffer.from(sig ?? "");
if (given.length !== expected.length || !timingSafeEqual(given, expected)) throw new Error("bad signature");
const c = JSON.parse(Buffer.from(body, "base64url"));
if (c.iss !== iss || c.aud !== aud) throw new Error("wrong issuer or audience");
if (typeof c.exp !== "number" || c.exp <= now) throw new Error("expired");
return c;
}
const secret = "demo-secret-at-least-32-bytes-long!!";
const now = Math.floor(Date.now() / 1000);
const token = issue({ iss: "https://auth.example", aud: "orders-api", sub: "user-42", exp: now + 300 }, secret);
console.log(verify(token, secret, { iss: "https://auth.example", aud: "orders-api" }).sub); // user-42
const forged = b64({ alg: "none", typ: "JWT" }) + "." + token.split(".")[1] + ".";
try { verify(forged, secret, { iss: "https://auth.example", aud: "orders-api" }); }
catch (e) { console.log(e.message); } // unexpected alg
try { verify(token, secret, { iss: "https://auth.example", aud: "billing-api" }); }
catch (e) { console.log(e.message); } // wrong issuer or audienceOpenID Connect
- What does OpenID Connect add to OAuth? An identity layer: the
openidscope, an ID token with standard claims about the user and the login event, a UserInfo endpoint, and a discovery document at/.well-known/openid-configurationlisting endpoints and keys. - How does a client validate an ID token? Check the signature with the issuer's keys,
issequals the expected issuer,audcontains its client id,expis in the future, andnoncematches the value it sent. - What is the nonce for? It ties the ID token to the specific login request, preventing replay of a token captured from another session.
- Why not use an access token to log a user in? Access tokens are meant for the API, may be opaque, and say nothing reliable to the client about who logged in. Using them for login lets a token issued to another app be replayed to yours.
- OIDC versus SAML? Both do single sign-on. SAML is XML-based and common in enterprise web SSO; OIDC is JSON and JWT based, works well for mobile and SPAs, and is the usual choice for new systems.
Sessions versus tokens, and storage in the browser
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Server sessions or JWTs for a web app? | Architecture | A session id in a cookie with state on the server is simple, easy to revoke and fine for one web app. Self-contained tokens suit many independent APIs and services. Many systems use both: a session for the browser and tokens between services. |
| Where should a single-page app keep tokens? | Browser security | localStorage is readable by any script, so an XSS bug steals the token. Memory-only storage is safer but lost on reload. The backend-for-frontend pattern keeps tokens on a server and gives the browser only an HttpOnly session cookie. |
| Which cookie flags matter? | Cookies | HttpOnly (no script access), Secure (HTTPS only), SameSite=Lax or Strict (limits cross-site sending and CSRF), plus a narrow path and domain and a sensible lifetime. |
| Cookies are sent automatically. Doesn't that mean CSRF? | CSRF | It can. SameSite cookies, CSRF tokens on state-changing requests, and checking the Origin header defend against it. Bearer tokens in an Authorization header are not sent automatically, which is why they are not exposed to CSRF in the same way. |
| How would you secure calls between microservices? | Service identity | Client credentials tokens with narrow scopes and audiences per service, or mutual TLS with workload identities, plus propagating the end user's identity in a separate, verified token where needed. |
| How do you design "Sign in with Google" for a mobile app? | End-to-end design | Authorization code with PKCE through the system browser (not an embedded web view), a claimed HTTPS redirect or app link, ID token validation on your backend, then your own session or tokens for your API. |
Common security mistakes interviewers ask about
- Accepting any algorithm the token header names. Pin algorithms and keys on the server.
- Skipping audience or issuer checks. Tokens meant for other services or tenants then work on yours.
- Long-lived access tokens with no revocation plan. A leak stays useful for days.
- Putting personal or secret data in JWT payloads. Anyone with the token can read them.
- Wildcard or prefix-matched redirect URIs. They turn an open redirect into stolen authorization codes.
- Missing `state` or nonce checks. They open login CSRF and token replay.
- Logging tokens, or sending them in URLs. Query strings end up in logs, proxies and browser history.
- Using an embedded web view for login in mobile apps. The app can read the user's credentials, and users cannot see the real address bar.
Fictional example
- Interviewer
- Our SPA stores a JWT access token in localStorage, and an XSS bug just leaked one. Talk me through the impact and the fix.
- Candidate
- Because it is a bearer token, the attacker can call every API that accepts it, with that user's scopes, until it expires, and our APIs validate it locally, so we cannot revoke it on the spot. First, the immediate response: fix the XSS, rotate the signing key if there is any chance it leaked, which invalidates every token, and revoke that user's refresh tokens. Then the structural fixes. Shorten access token lifetime to minutes so a leak expires quickly. Move tokens out of reach of scripts with a backend-for-frontend: the browser holds only an HttpOnly, Secure, SameSite cookie, and the BFF holds the tokens. Turn on refresh token rotation with reuse detection. For high-risk APIs, consider sender-constrained tokens with DPoP so a copied token is useless without the client's key. And add a content security policy to make the next XSS harder.
How to prepare for OAuth and JWT questions
- Draw the code flow with PKCEBrowser, client, authorization server and API, with every redirect and back-channel call labeled. Practice until you can do it in two minutes.
- Decode real tokensSign in to a test app with a developer identity provider and decode the ID and access tokens. Read every claim and say what checks a server should run.
- Learn the grant decision tableFor each app type (server web app, SPA, mobile, CLI, TV, service-to-service), name the grant and explain why the others are wrong.
- Collect the mistakesFor each item in the mistakes list, prepare the attack in one sentence and the defense in one sentence.
- Prepare a design answerPick one scenario, such as protecting microservices or adding social login to a mobile app, and rehearse it end to end, including logout and revocation.
OAuth builds on the transport layer: computer networks interview questions covers TLS, cookies, CORS and HTTP itself. In Java shops these questions often continue into Spring Security, so see Spring Boot interview questions. The backend developer interview questions page puts authentication in the context of a full API design round.
Security answers need exact words, so rehearse them and read them back. Natively, an AI interview assistant for Mac and Windows, transcribes a mock identity round as you draw a flow, can suggest an answer to compare against yours, and reads a token, a diagram or code from a screenshot so you can check what you missed. On Pro or the free trial it can draw on the résumé and job description you add, and each session's transcript and notes are kept for review.
Questions people ask
What is the difference between OAuth and OpenID Connect?
OAuth 2.0 is an authorization framework that lets an app get access tokens for an API. OpenID Connect adds authentication on top, with an ID token that tells the app who signed in.
What is PKCE and why is it needed?
Proof Key for Code Exchange binds an authorization code to the client that requested it. The client sends a hash of a secret verifier first and the verifier itself at the token exchange, so an intercepted code is useless.
Is a JWT encrypted?
A standard signed JWT is only base64url encoded, so anyone holding it can read the claims. Never put secrets in it, and always verify the signature, algorithm, issuer, audience and expiry.
Should I use sessions or JWTs?
A server-side session in a secure cookie is simple and easy to revoke for a single web app. Self-contained tokens suit many independent APIs. Many systems use sessions for the browser and tokens between services.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
