Complete Interview Questions & Answer Bank
50 curated technical interview questions and answers covering authentication fundamentals, JWT mechanics, OAuth 2.0 grant types, OIDC specifications, security vulnerabilities, and production architecture patterns.
Q2: What is a JSON Web Token (JWT) and what are its three structural components?
A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained format for securely transmitting information between parties as a JSON object.
A JWT consists of three parts separated by dots (.):
- Header: Specifies the token type (
JWT) and signing algorithm (HS256,RS256). - Payload: Contains the claims (statements about an entity, e.g., user ID, roles, expiration time).
- Signature: Cryptographic signature generated by combining the Base64URL-encoded header and payload with a secret or private key.
// Base64URL Encoded JWT String:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
// Decoded Header:
{
"alg": "HS256",
"typ": "JWT"
}
// Decoded Payload:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}Header and Payload are Base64URL encoded JSON strings. The signature is computed using the secret key over the encoded header and payload.
A JWT consists of three Base64URL encoded strings separated by dots: Header, Payload, and Signature.
JWT payloads are encoded, not encrypted by default; sensitive raw data must never be placed inside a standard JWT.
Q3: What are the standard JWT Registered Claims and their definitions?
RFC 7519 defines a set of optional, standardized claim keys known as Registered Claims to ensure interoperability across applications:
iss(Issuer): Identifies the principal that issued the JWT.sub(Subject): Identifies the principal that is the subject of the JWT (e.g., User ID).aud(Audience): Identifies the recipients that the JWT is intended for.exp(Expiration Time): Identifies the expiration time on or after which the JWT MUST NOT be accepted.nbf(Not Before): Identifies the time before which the JWT MUST NOT be accepted.iat(Issued At): Identifies the time at which the JWT was issued.jti(JWT ID): Provides a unique identifier for the JWT (used to prevent replay attacks).
Registered claims are standardized shorthand keys designed for interoperable security checks.
Always enforce
expvalidation on backend resource servers to limit the exposure window of compromised tokens.
Q4: What is the difference between Symmetric (HS256) and Asymmetric (RS256) JWT signing?
- HS256 (HMAC with SHA-256): Uses a single shared secret key for both signing and verifying the token. Both the Auth Server and Resource Server must share and store the identical secret key securely.
- RS256 (RSA Signature with SHA-256): Uses an asymmetric key pair. The Authorization Server signs the JWT using its Private Key, while external Resource Servers verify the signature using the Authorization Server's public key (fetched via JWKS).
HS256 requires sharing secret keys between Auth Server and APIs; RS256 requires exposing only public keys.
RS256 is the industry standard for microservice architectures and third-party API consumers.
Q5: Compare Stateful Session Authentication with Stateless JWT Authentication.
In Stateful Session Authentication, the server generates a random Session ID upon login, stores session state in memory/database (e.g., Redis), and returns the Session ID in an HTTP cookie. On each request, the server looks up the Session ID in the database.
In Stateless JWT Authentication, all user context and permissions are encoded directly inside the signed JWT payload returned to the client. Resource servers validate the token cryptographically without making database lookups.
Sessions vs JWTs
Server-side Database vs Client-side Payload
Sessions require centralized cache lookups; JWTs self-contain user state.
Instant (Delete session record) vs Complex (Requires blacklist)
Session revocation takes effect immediately; JWTs remain valid until exp unless blacklisted.
Requires Shared Session Store vs Inherently Scalable
JWTs allow any microservice instance to validate requests independently.
Session authentication enables instant server-side revocation but creates database lookup bottlenecks.
JWT authentication scales effortlessly across microservices but complicates token revocation.
Q6: What are the four core roles defined in the OAuth 2.0 framework (RFC 6749)?
OAuth 2.0 defines four distinct roles to separate token authorization from resource handling:
- Resource Owner: The entity capable of granting access to a protected resource (typically the end user).
- Resource Server: The API server hosting the protected user resources, capable of accepting and responding to protected resource requests using access tokens.
- Client: The application making resource requests on behalf of the Resource Owner with its authorization.
- Authorization Server: The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.
OAuth 2.0 strictly decouples the Authorization Server from the Resource Server.
Clients interact with Resource Servers strictly using access tokens issued by the Authorization Server.
Q8: What are the main OAuth 2.0 Grant Types and when should each be used?
OAuth 2.0 provides several grant types tailored for different application architectures:
- Authorization Code Grant + PKCE: For Single Page Apps (SPAs), Mobile Apps, and Web Applications.
- Client Credentials Grant: For machine-to-machine (M2M) communication without user context.
- RefreshToken Grant: Used by clients to obtain new access tokens when current access tokens expire.
- Resource Owner Password Credentials (Deprecated): Legacy flow where user gives credentials directly to client; strictly disallowed in OAuth 2.1.
- Implicit Grant (Deprecated): Legacy SPA flow that returned tokens in URL fragments; completely removed in OAuth 2.1 in favor of PKCE.
Authorization Code + PKCE is the universal standard for user-facing applications.
Client Credentials Grant is intended exclusively for server-to-server daemon processes.
Q9: How does the OAuth 2.0 Client Credentials Grant work for Machine-to-Machine (M2M) communication?
The Client Credentials Grant is used when the client application requests access to resources under its own control, rather than requesting access to a specific user's private data.
Execution Flow:
- The confidential client transmits its
client_idandclient_secretdirectly to the Authorization Server's/tokenendpoint using HTTP Basic Auth or request body parameters (grant_type=client_credentials). - The Authorization Server authenticates the client credentials.
- The Authorization Server issues an Access Token containing application-level scopes.
- The client uses the Access Token to call backend APIs.
POST /oauth/token HTTP/1.1
Host: auth.example.com
Authorization: Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&scope=read%3Areports%20write%3AlogsThe client authenticates using its secret and requests access tokens bound to machine-level API scopes.
Client Credentials Grant involves no end-user interaction or browser redirects.
Must be used strictly by confidential backend servers capable of securing client secrets.
Q10: What is OpenID Connect (OIDC) and how does it extend OAuth 2.0?
OpenID Connect (OIDC) is an identity layer built on top of the OAuth 2.0 framework. While OAuth 2.0 handles authorization (granting access keys to resources), OIDC extends it to perform user authentication.
OIDC Additions to OAuth 2.0:
- ID Token: A standardized JWT containing user identity profile attributes (claims like
sub,email,name). - UserInfo Endpoint: A protected API endpoint returning detailed user profile attributes.
- Standardized Scopes: Predefined scopes like
openid,profile,email.
OIDC = OAuth 2.0 (Authorization) + ID Token (Authentication).
Always include the
openidscope in authorization requests to trigger OIDC behavior.
Q11: What are the differences between Access Tokens, ID Tokens, and Refresh Tokens?
Each token type serves a distinct security purpose in modern token-based architectures:
Token Characteristics Matrix
For API Resource Servers | Short-Lived (5-15 mins)
Used to access protected APIs. Opaque or JWT. Contains scopes and permission claims.
For Client Application | Read Once upon Auth
Must be a JWT. Contains profile assertions about the user for the UI to consume.
For Authorization Server | Long-Lived (Days/Months)
Used to fetch new Access Tokens silently without forcing user re-authentication.
Access tokens authorize API calls; ID tokens inform client applications about user profile details.
Client applications must never send ID Tokens to API Resource Servers for authorization purposes.
Q12: How does Refresh Token Rotation with Reuse Detection safeguard single page applications?
Refresh Token Rotation ensures that every time a client exchanges a Refresh Token for a new Access Token, the Authorization Server invalidates the old Refresh Token and returns a brand new Refresh Token.
Automatic Reuse Detection:
If an attacker steals an old Refresh Token and attempts to reuse it after the legitimate client has already exchanged it, the Authorization Server detects that a revoked token was presented. It immediately invalidates the entire refresh token family, revoking access for both the legitimate user and the attacker.
Refresh Token Rotation issues a new refresh token on every single token refresh request.
Reuse detection revokes the entire token hierarchy if a previously invalidated refresh token is presented.
Q13: Where should JWTs be stored in browser-based applications to prevent XSS and CSRF?
Browser token storage involves trading off Cross-Site Scripting (XSS) risks against Cross-Site Request Forgery (CSRF) risks:
- LocalStorage / SessionStorage: Vulnerable to XSS attacks. Any malicious JavaScript running in the domain context can read stored tokens.
- Standard HTTP Cookies: Vulnerable to CSRF attacks unless protected with proper
SameSiteflags and anti-CSRF tokens. httpOnly,Secure,SameSite=StrictCookies: Best Security Standard.httpOnlyprevents client-side JavaScript from reading the cookie (mitigating XSS extraction), whileSecureforces HTTPS transmission andSameSitemitigates CSRF.
Never store access or refresh tokens in LocalStorage due to script access XSS risks.
Store tokens in
httpOnly,Secure,SameSite=Strictcookies or maintain access tokens strictly in memory.
Q14: Explain the JWT `alg: none` security vulnerability and how to defend against it.
The JWT specification includes an alg: none option intended for debugging or unsecured environments. In early JWT libraries, if an attacker modified an existing token payload (e.g., changing role: user to role: admin), stripped the signature section, and set "alg": "none" in the header, naive verification logic would accept the token as valid without checking the signature.
Defense:
- Never allow the verification engine to dynamically accept the
algheader from the unverified incoming token. - Explicitly enforce expected algorithms in server verification configurations (e.g.,
jwt.verify(token, key, { algorithms: ['RS256'] })).
The
alg: noneexploit allows attackers to bypass signature validation entirely.Hardcode explicitly allowed verification algorithms in server configuration.
Q15: What is the JWT Algorithm Confusion Attack (RSA vs HMAC) and how is it mitigated?
In an Algorithm Confusion Attack, an API expects an RS256 token signed with the Authorization Server's Private Key and verified using its Public Key.
An attacker captures the public key (which is publicly available), crafts a malicious payload, sets the header to "alg": "HS256" (Symmetric HMAC), and signs the payload using the Public Key string as the symmetric secret key.
If the server library uses a generic verification routine that blindly trusts the token's alg header, it uses the local public key string as an HMAC secret, validating the forged signature successfully.
Algorithm confusion tricks asymmetric RS256 verification code into executing symmetric HS256 validation using public keys.
Always restrict API verification logic to explicit algorithm white-lists.
Q16: How can you revoke stateless JWT access tokens before their natural expiration?
Because JWTs are stateless, instant token revocation requires adding specific tracking mechanisms:
- Short Lifespans + Refresh Tokens: Keep access token lifespans extremely short (e.g., 5 minutes); revoke access by invalidating the refresh token on the Auth Server.
- Token Denylist / Blacklist in Redis: Store revoked JWT
jti(JWT ID) claims in an in-memory Redis cache with TTL equal to the remaining expiration time. APIs check Redis during request processing. - User Token Versioning: Store an integer
token_versionon the User database record and inside the JWT payload. Incrementing the databasetoken_versionimmediately invalidates all active tokens for that user.
Keep JWT lifespans short to minimize the window of compromise.
Use Redis
jtiblacklists ortoken_versioncounters for instant multi-device logout enforcement.
Q17: What is a JSON Web Key Set (JWKS) and how is key rotation handled dynamically?
A JWKS (RFC 7517) is a set of public keys represented as a JSON structure exposed by an Authorization Server at a public URL (e.g., /.well-known/jwks.json).
Resource Servers consume JWKS endpoints to dynamically fetch public keys needed to verify incoming RS256/ES256 signatures.
Key Rotation Process:
- Each public key in a JWKS is assigned a unique Key ID (
kid). - JWT headers contain a matching
kidheader property indicating which key was used to sign the token. - During key rotation, the Auth Server introduces a new key pair, publishes the new public key in the JWKS, and signs new tokens with the new
kidwhile keeping old keys in the JWKS for legacy tokens.
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"alg": "RS256",
"kid": "auth-key-2026-v1",
"n": "u1W_z...",
"e": "AQAB"
}
]
}Resource servers match the incoming JWT header kid parameter against the keys array to pick the correct public key.
JWKS enables dynamic public key distribution and seamless cryptographic key rotation.
APIs locate verification keys by matching the
kidproperty in the JWT header against JWKS entries.
Q18: What is Cross-Site Request Forgery (CSRF) and how do cookie-based authentication systems defend against it?
CSRF occurs when a malicious website tricks a user's browser into automatically sending authenticated HTTP requests (including auto-attached cookies) to a target application where the user is currently logged in.
CSRF Defenses:
SameSiteCookie Attribute: SettingSameSite=StrictorSameSite=Laxprevents browsers from sending cookies on cross-site subrequests.- Anti-CSRF Tokens (Synchronizer Token Pattern): Server generates a unique cryptographic token stored in the session and requires it in custom request headers (
X-CSRF-Token). - Custom Header Verification: APIs requiring custom headers (e.g.,
Authorization: Bearer <token>) are immune to traditional browser form CSRF because cross-origin JS cannot set custom headers without failing CORS preflight checks.
CSRF targets automatically attached browser cookies; it does not impact header-based Bearer tokens.
Use
SameSite=Strictcookies alongside anti-CSRF tokens for cookie-authenticated APIs.
Q19: What is Cross-Site Scripting (XSS) and how does it compromise token authentication?
XSS occurs when an attacker successfully injects malicious client-side script code into a web application. If malicious code executes inside the victim's DOM, it possesses full access to page context.
Impact on Tokens:
- If tokens are stored in
LocalStorageorSessionStorage, injected script code readslocalStorage.getItem('token')and exfiltrates it to an attacker server. - If tokens are stored in
httpOnlycookies, JavaScript cannot read the token string directly. However, the attacker can still trigger authenticated fetch requests from within the DOM context while the session is active.
LocalStorage offers zero protection against XSS token exfiltration.
httpOnly cookies mitigate direct token script extraction during XSS attacks.
Q20: What is the Backend-for-Frontend (BFF) Pattern and how does it optimize SPA security?
The Backend-for-Frontend (BFF) security pattern introduces a lightweight server-side proxy component between a Single Page Application (SPA) and downstream microservices.
Operational Flow:
- The SPA interacts strictly with the BFF proxy using secure,
httpOnly,SameSiteencrypted session cookies. - The BFF server handles the OAuth 2.0 PKCE token exchange flow and stores Access/Refresh Tokens securely in server-side session memory.
- When the SPA calls an API, the BFF intercepts the cookie request, attaches the stored Bearer Access Token server-side, and proxies the request to the target backend API.
BFF isolates raw OAuth tokens entirely on the server side, keeping them out of browser DOM memory.
The browser talks to the BFF via httpOnly cookies, eliminating token theft via XSS.
Q21: What is the purpose of the OAuth 2.0 `state` parameter and how does it prevent CSRF?
The state parameter is an opaque, unguessable cryptographic token generated by the client application before initiating an authorization code redirect.
How it prevents CSRF in OAuth:
- The client generates a random state value, saves it in user session storage, and appends it to the
/authorizerequest URL. - The Authorization Server returns the identical
statestring in the redirect callback URL alongside theauthorization_code. - The client compares the returned
stateparameter against the value stored in the user's session before requesting tokens. - If an attacker attempts to force a victim to redeem a malicious authorization code, the
statevalues will not match, blocking the request.
The
stateparameter binds authorization responses to the specific browser session that initiated them.Always validate the returned
stateparameter string before exchanging authorization codes for tokens.
Q22: Compare Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC).
- RBAC (Role-Based Access Control): Assigns permissions to explicit roles (e.g.,
Admin,Editor,Viewer). Users are assigned roles, and authorization logic checks if the user possesses the required role to access a route (hasRole('ADMIN')). - ABAC (Attribute-Based Access Control): Evaluates dynamic rules combining subject attributes (user role, department), resource attributes (owner ID, sensitivity classification), and environmental context (ip_address, time_of_day, device_type).
RBAC vs ABAC
Static Role Checks vs Dynamic Policy Expressions
RBAC checks fixed roles; ABAC evaluates dynamic contextual conditions.
Simple to Implement vs Requires Policy Engine
RBAC uses straightforward role lists; ABAC requires engines like Open Policy Agent (OPA).
Coarse-Grained vs Fine-Grained Contextual Control
ABAC supports policies like 'Allow editing only during business hours if user is record owner'.
RBAC is ideal for straightforward coarse-grained role management.
ABAC provides dynamic context-aware authorization policies across complex enterprise domain models.
Q23: How does SAML 2.0 compare with OAuth 2.0 and OpenID Connect (OIDC)?
- SAML 2.0 (Security Assertion Markup Language): An XML-based enterprise federation standard primarily used for Single Sign-On (SSO) in legacy corporate environments. Exchanges XML assertions over heavy HTTP POST redirects.
- OAuth 2.0 / OIDC: A modern JSON/REST API-friendly framework built for web, mobile, and single-page applications. Uses lightweight JSON Web Tokens (JWT) and HTTPS Authorization headers.
SAML 2.0 relies on heavy XML payloads for legacy corporate enterprise SSO.
OIDC/OAuth 2.0 utilizes lightweight JSON payloads designed for modern APIs and mobile platforms.
Q24: What is a JWT Replay Attack and how do `jti` claims and nonces mitigate it?
A Replay Attack occurs when an attacker intercepts a valid signed JWT transmitted across a network and retransmits it multiple times to unauthorized API endpoints.
Mitigation Strategies:
- Short Expiration Times (
exp): Reduces the time window during which intercepted tokens remain usable. - Unique Token Identifiers (
jti): Auth server includes a unique UUID inside thejticlaim. API gateways record usedjtitokens in a cache (e.g., Redis) and reject duplicated submissions. - Client Nonces (
nonce): Used in OIDC to bind the authorization request to the resulting ID token signature.
Replay attacks involve retransmitting intercepted valid tokens.
Use unique
jticlaims and short token expiration lifetimes to block token replay.
Q25: What is the difference between Opaque Access Tokens and Self-Contained JWT Bearer Tokens?
- Opaque Access Tokens: Cryptographically random reference strings (e.g.,
str_981231a...). They carry no embedded payload information. Resource Servers must execute an HTTP introspect call back to the Auth Server to validate the token on every request. - Self-Contained JWT Bearer Tokens: JSON Web Tokens containing identity and permission claims signed cryptographically. Resource Servers validate tokens locally using public keys without contacting the Authorization Server.
Opaque tokens require network introspection on every API call, offering central control and instant revocation.
JWTs validate locally using public keys, maximizing performance and microservice independence.
Q26: What is OAuth 2.0 Token Introspection (RFC 7662)?
Token Introspection defines an RFC-standardized HTTP POST protocol enabling Resource Servers to query the Authorization Server to check the active status and meta-claims of an incoming access token.
It is mandatory when using Opaque Access Tokens and optional when Resource Servers require real-time revocation verification for JWTs.
// POST /introspect HTTP/1.1
// Host: auth.example.com
// Authorization: Basic YXBpX3NlcnZlcjpzZWNyZXQ=
// Content-Type: application/x-www-form-urlencoded
// token=opaque_token_string_8891
// Introspection JSON Response:
{
"active": true,
"scope": "read write",
"client_id": "app_client_123",
"sub": "usr_99812",
"exp": 1776000000
}The resource server submits the token string to the authorization server to confirm validity and retrieve associated scopes.
Introspection allows resource servers to validate opaque tokens dynamically.
Introduces network latency overhead on API calls compared to local JWT public key verification.
Q27: How does OAuth 2.0 Token Revocation (RFC 7009) operate?
Token Revocation defines a standardized HTTP API endpoint (/revoke) allowing client applications to explicitly inform the Authorization Server that a user has logged out or that a token is no longer needed.
When a client submits an Access Token or Refresh Token to /revoke, the Authorization Server invalidates the token and its associated token family across all cluster nodes.
RFC 7009 provides a standard mechanism for explicit client-side logout token invalidation.
Revoking a parent refresh token automatically revokes all associated child access tokens.
Q28: What is the difference between JSON Web Signatures (JWS) and JSON Web Encryption (JWE)?
- JWS (JSON Web Signature): Encodes header and payload using Base64URL and appends a digital signature. Payload data is clearly readable by anyone who decodes the Base64 string, but signature validation guarantees data integrity and tamper-resistance.
- JWE (JSON Web Encryption): Cryptographically encrypts the payload content using symmetric/asymmetric algorithms. Payload data is completely hidden from unauthorized parties lacking the private decryption key.
JWS provides tamper-proof integrity (Data is readable by all); JWE provides confidential privacy (Data is encrypted).
Use JWE when transmitting sensitive Personally Identifiable Information (PII) inside token payloads.
Q29: What are Session Hijacking and Session Fixation attacks, and how are they prevented?
- Session Hijacking: An attacker steals a legitimate user's active session ID or access token and impersonates them.
- Session Fixation: An attacker sets a known session ID in a victim's browser before login; when the victim logs in, the attacker uses the predefined session ID to access the account.
Mitigations:
- Regenerate session IDs and tokens immediately upon successful user login.
- Enforce strict HTTPS using HSTS (
Strict-Transport-Security). - Bind tokens to TLS client fingerprints or DPoP (Demonstrating Proof-of-Possession).
Regenerate session identifiers immediately upon user privilege state changes or login.
Enforce HTTPS across all application routes to prevent token interception.
Q30: What is DPoP (Demonstrating Proof-of-Possession, RFC 9449) and how does it prevent token theft?
DPoP (RFC 9449) cryptographically binds an Access Token to a specific client's public/private key pair.
How DPoP Works:
- The client generates an ephemeral public/private key pair.
- On every API request, the client signs a custom HTTP header (
DPoP) containing a proof JWT signed with its private key. - The API server verifies that the incoming Bearer Access Token is cryptographically bound to the public key in the
DPoPheader. - If an attacker steals the Access Token, they cannot use it on another device without possessing the client's private key.
DPoP binds access tokens to a client's private key, rendering stolen tokens unusable on attacker devices.
Eliminates bearer token vulnerability risks for high-security financial and healthcare APIs.