Authentication & Authorization Interview Questions and Answers
Sessions, tokens, OAuth 2.0, OIDC, RBAC and common attacks.
Whether you are preparing for entry-level Authentication & Authorization interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 What is the difference between authentication and authorization? Easy
Authentication (authn) establishes who the caller is: verifying a password, a session cookie, a token or a certificate. Authorization (authz) decides what that identified caller is allowed to do.
authn: "You are user 42." -> 401 if missing
authz: "User 42 may delete this order." -> 403 if denied
Authentication normally happens once per session or token, while authorization is evaluated per request or per resource. A common bug is stopping at authentication and forgetting authorization, allowing any logged-in user to access another user's data (an insecure direct object reference). Best practice is to enforce authorization close to the data, for example scoping every query by the caller's tenant or user id, rather than trusting an id supplied by the client. Keep identity data in the token or session and derive permissions from a central policy or role service.
2 Session-based versus token-based authentication: what are the trade-offs? Easy
Session-based authentication stores session state on the server and gives the client an opaque session identifier in a cookie. It is easy to revoke (delete the session), supports immediate logout of all devices, and keeps sensitive data server-side. It requires shared session storage such as Redis when horizontally scaled, and can be vulnerable to CSRF if cookies are used.
Token-based authentication, typically JWT, is stateless: the server verifies a signed token without a lookup. This scales well and works across services and mobile clients, and tokens in an Authorization header are not sent automatically, reducing CSRF risk. The trade-off is revocation: a valid JWT stays valid until it expires, so you need short lifetimes, refresh tokens and denylists.
Authorization: Bearer <jwt>
Cookie: session=opaque-id; HttpOnly; Secure; SameSite=Lax
Many systems combine both: short-lived access tokens for APIs and a server-side refresh or session record for control.
3 What is a JWT and what are its parts? Easy
A JSON Web Token is a compact, URL-safe token with three base64url parts separated by dots: header, payload and signature.
eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOiI0MiJ9 . signature
header payload signature
The header names the signing algorithm and type. The payload holds claims such as iss (issuer), sub (subject), aud (audience), exp (expiry), iat, nbf and custom claims like roles. The signature protects integrity: anyone can decode the payload, so never put secrets in it.
Key points: a JWT is signed, not encrypted (JWE is the encrypted variant). Verification must check the signature with the expected algorithm and validate exp, nbf, iss and aud. Because the server trusts the token without a lookup, revocation requires short lifetimes plus a denylist or a version claim. Never trust a payload you have not verified.
4 What is the difference between OAuth 2.0 and OIDC? Medium
OAuth 2.0 is an authorization framework for delegated access. It lets a user grant a third-party application limited access to a resource without sharing the password, and the result is an access token used to call APIs. OAuth 2.0 does not define how to authenticate a user or how to convey their identity.
OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0. It adds an ID token (a JWT with standardized identity claims), a /userinfo endpoint, standardized scopes such as openid profile email, and a discovery document at /.well-known/openid-configuration.
OAuth 2.0: get an access token to call an API
OIDC: get an ID token that tells you who logged in
Use OIDC when you need "sign in with" behavior or federated identity. Use plain OAuth 2.0 for machine-to-machine API authorization. A frequent mistake is treating an OAuth access token as proof of user identity; that is what the ID token is for.
5 Explain the OAuth 2.0 authorization code flow with PKCE. Medium
It is the recommended flow for web, mobile and single-page applications.
- The client generates a random
code_verifier, hashes it to acode_challenge, and redirects the user to the authorization endpoint with the client id, redirect URI, scope, state and challenge. - The user authenticates and consents.
- The authorization server redirects back with an authorization code and the original
state. - The client exchanges the code at the token endpoint, sending the
code_verifier. - The server verifies the verifier against the stored challenge and returns tokens.
GET /authorize?response_type=code&client_id=app
&code_challenge=...&code_challenge_method=S256&state=xyz
PKCE prevents an attacker who intercepts the authorization code from redeeming it, because they lack the verifier. Always validate state for CSRF, use exact registered redirect URIs, and avoid the deprecated implicit flow that exposes tokens in the URL.
6 Compare RBAC and ABAC for authorization. Medium
Role-Based Access Control assigns permissions to roles and roles to users, for example admin can delete any order. It is simple to reason about, easy to audit and a good default for most applications. Its weakness is role explosion and coarse decisions: rules like "editors can edit posts they own in their own department" do not fit cleanly.
Attribute-Based Access Control evaluates policies over attributes of the user, resource, action and environment, for example "allow if user.department == resource.department and time is within business hours". It is fine-grained and expressive, which suits regulated or multi-tenant systems, but policies are harder to write, test and reason about, and can be expensive to evaluate.
RBAC: if (user.roles.includes("editor")) allow
ABAC: if (user.dept === doc.dept && doc.state === "draft") allow
Many systems combine them: roles for coarse access, attributes for per-resource decisions, and relationship checks such as ownership. Evaluate centrally and log decisions for auditability.
7 What is the difference between an access token and a refresh token? Medium
An access token is short-lived, typically minutes, and is presented to APIs to authorize requests. If it leaks, the exposure window is small. It is usually a JWT so resource servers can verify it without a central lookup.
A refresh token is long-lived and is used only against the authorization server to obtain new access tokens, so the user does not re-authenticate constantly. It is an opaque credential, stored securely server-side or in a protected client store, and should never be sent to resource servers.
POST /token
grant_type=refresh_token&refresh_token=...&client_id=app
Best practices: keep access tokens in memory where possible, rotate refresh tokens on each use, bind them to the client, and revoke the whole chain if a used refresh token is replayed, which signals theft. Store browser tokens in HttpOnly, Secure cookies when feasible rather than localStorage, and always use TLS.
8 What are the most common JWT security pitfalls? Medium
- Accepting the
nonealgorithm or trusting the token header for algorithm selection, which enables algorithm confusion attacks. Pin the expected algorithm server-side. - Not verifying the signature at all, or using a weak shared secret that can be brute-forced.
- Storing JWTs in
localStorage, where any XSS can exfiltrate them. Prefer HttpOnly, Secure cookies for browsers. - Long expiry with no revocation strategy; a stolen token is valid until it expires. Use short lifetimes and refresh tokens.
- Putting sensitive data in the payload and forgetting it is only base64url encoded, readable by anyone.
- Skipping validation of
exp,nbf,issoraud, so tokens from another issuer or audience are accepted. - Using symmetric HS256 across many services, sharing the signing secret widely.
jwt.verify(token, publicKey, { algorithms: ["RS256"], issuer, audience });
Review these in security tests and prefer battle-tested libraries over hand-rolled token handling.
9 What is CSRF and how do you prevent it? Medium
Cross-Site Request Forgery tricks a logged-in user's browser into sending an authenticated request to your site. Because browsers attach cookies automatically, a malicious page can trigger a state-changing request without the user's intent.
<img src="https://bank.example/transfer?to=attacker&amount=1000">
Preventions:
- Set cookies
SameSite=LaxorStrictso they are not sent on cross-site requests. - Use anti-CSRF tokens: a random value stored in the session and required in the request body or a custom header, validated server-side.
- Check the
OriginorRefererheader on state-changing requests. - Require a non-simple content type such as JSON, which triggers a preflight.
- Prefer
Authorizationheader tokens over cookies for APIs, since headers are not attached automatically.
Note that XSS defeats most CSRF defences, so prevent XSS too. Combine SameSite cookies with tokens for defence in depth.
10 How does XSS relate to authentication security? Medium
Cross-Site Scripting lets an attacker run JavaScript in your origin. Once that happens, the script can read anything the page can read, including tokens in localStorage or sessionStorage, and can make authenticated requests as the user. It can also steal CSRF tokens by reading the DOM, defeating token-based CSRF defences.
Preventions:
- Encode output contextually and avoid
innerHTML; prefer safe DOM APIs and templating that auto-escapes. - Sanitize rich user content with an allow-list library.
- Add a strict Content Security Policy that blocks inline and third-party scripts.
- Mark session cookies
HttpOnlyso JavaScript cannot read them, andSecureso they only travel over TLS. - Use short-lived access tokens and rotate them.
Content-Security-Policy: default-src 'self'; script-src 'self'
Because XSS can fully impersonate a user, treat it as an authentication threat, not just a rendering bug, and test for it in code review and automated scans.
11 How do you revoke a JWT before it expires? Hard
A stateless JWT cannot be un-issued, so revocation needs supporting state.
Options:
- Denylist: store revoked token identifiers (
jti) until theirexp, and check on each request. Simple but adds a lookup and grows with volume. - Token version or
pwd_atclaim: keep a per-user counter or password-change timestamp in the user record; reject tokens whose claim is older. A single update revokes all of a user's tokens. - Short access tokens plus refresh-token revocation: keep access tokens to minutes and revoke the refresh token server-side, so the session dies quickly. This is the most common production approach.
- Central introspection: resource servers call the authorization server (as with opaque tokens) to validate, trading statelessness for control.
if (token.exp < now) reject
if (denylist.has(token.jti)) reject
if (token.ver < user.tokenVersion) reject
For immediate global logout, the version or session-store approach is cleaner than a large denylist. Cache validation results briefly to limit overhead.
12 How would you design machine-to-machine authentication? Hard
For service-to-service calls, avoid shared static credentials and long-lived secrets.
- OAuth 2.0 client credentials: each service is a registered client with a client id and secret, and obtains a short-lived access token scoped to what it needs. Prefer private key JWT or mTLS client authentication over a shared secret.
- Mutual TLS: both sides present certificates, giving cryptographic service identity. Short-lived certificates issued by an internal CA or SPIFFE identities work well in a service mesh.
- Workload identity: cloud platforms issue short-lived tokens bound to the workload's identity, removing static keys.
POST /token
grant_type=client_credentials&scope=orders:read
Apply least privilege with narrow scopes and audiences, rotate secrets automatically, store them in a secret manager, and never bake them into images. Add authorization checks on the callee, not just authentication, and audit token issuance. For third-party integrations, prefer per-tenant credentials so one leak does not compromise everyone.
Frequently Asked Questions About Authentication & Authorization Interviews
What do hiring managers evaluate in Authentication & Authorization technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing Authentication & Authorization questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.