Authentication — Common Interview Questions and Answers
1. What is authentication vs authorization?
- Authentication: Verifying who the user is (identity). Examples: login with password, biometrics, SSO.
- Authorization: Deciding what the user is allowed to do (permissions). Examples: role-based access (admin vs user), resource-level checks.
“AuthN” = identity; “AuthZ” = permissions. Authentication usually comes first; then authorization uses that identity.
2. What are common authentication methods?
- Password-based: Username/email + password; often with hashing (e.g. bcrypt, Argon2) and salt.
- Token-based: After login, client gets a token (e.g. JWT, opaque) and sends it (e.g.
Authorization: Bearer <token>). - Session-based: Server stores session (e.g. in DB or Redis); client sends session id (cookie or header).
- OAuth 2.0 / OIDC: Delegated auth; user signs in at IdP, app gets tokens.
- API keys: Long-lived secret for machine-to-machine or simple app access.
- MFA/2FA: Second factor (TOTP, SMS, hardware key) in addition to password.
3. What is JWT and how is it used for authentication?
JWT (JSON Web Token) is a compact, signed (and optionally encrypted) format with three parts: header.payload.signature, base64url-encoded.
- Payload usually includes:
sub(user id),exp(expiry),iat(issued at), and custom claims. - Signature (e.g. HMAC-SHA256 or RSA) lets the server verify the token wasn’t tampered with.
- Client sends it in
Authorization: Bearer <token>.
Pros: Stateless; works across services; no server-side session store. Cons: Hard to revoke before expiry (use short expiry + refresh tokens or a blocklist); payload is readable unless encrypted (JWE).
4. What is the difference between session-based and token-based (e.g. JWT) authentication?
| Aspect | Session-based | Token-based (e.g. JWT) |
|---|---|---|
| Storage | Session on server (DB/Redis) | Token on client |
| State | Stateful (server stores session) | Stateless (verify signature) |
| Revocation | Easy (delete session) | Hard (until expiry or blocklist) |
| Scaling | Need shared or sticky session | No server state per user |
| Cross-domain | Cookie issues across domains | Header works across domains |
Use sessions when you need instant logout/revocation; use tokens when you need stateless or cross-service auth.
5. How do you securely store passwords?
- Never store plain text or only base64.
- Use a slow, adaptive hash: bcrypt, scrypt, or Argon2 (with a cost factor).
- Use a unique salt per password (stored with the hash).
- Optionally use pepper (secret key) in addition to salt.
# Conceptually
stored = hash_function(password + unique_salt, cost=12)
# Verify: hash(provided_password, same_salt) == stored
6. What are refresh tokens and access tokens?
- Access token: Short-lived (e.g. 15 min), used for API requests. If stolen, window of abuse is limited.
- Refresh token: Long-lived (e.g. days/weeks), used only to get new access tokens; stored more securely (e.g. httpOnly cookie, secure storage in apps).
Flow: Client sends refresh token to a dedicated endpoint; server validates it and returns a new access (and optionally refresh) token. This limits exposure of long-lived credentials while keeping the user logged in.
7. What is OAuth 2.0 and when is it used?
OAuth 2.0 is a authorization framework for letting a user grant a client app limited access to their resources (e.g. at another service) without giving the app the user’s password.
Use cases: “Login with Google/GitHub”, “Allow this app to read my calendar”. It defines roles (resource owner, client, authorization server, resource server), flows (authorization code, client credentials, etc.), and tokens. It is not an authentication protocol by itself; OpenID Connect (OIDC) adds identity on top.
8. What is the difference between OAuth 2.0 and OpenID Connect (OIDC)?
- OAuth 2.0: About authorization (“this app can access my X”). Returns access token (and optionally refresh token).
- OpenID Connect (OIDC): Built on OAuth 2.0; adds authentication (“who is the user?”). Adds ID token (JWT with identity claims:
sub,email, etc.) and userinfo endpoint.
So: OAuth2 = access to resources; OIDC = sign-in + identity + access.
9. What is the OAuth 2.0 authorization code flow (with PKCE)?
- App redirects user to authorization server (e.g. login provider).
- User logs in and consents; server redirects back with a code (short-lived, one-time).
- App exchanges code (+
code_verifierin PKCE) for tokens at token endpoint (server-side or with PKCE from public clients). - App uses access token for API calls; refresh token to get new access tokens.
PKCE (Proof Key for Code Exchange): Client generates code_verifier and sends code_challenge with the auth request; later sends code_verifier at token exchange. Protects against code interception (e.g. mobile/public clients).
10. What is MFA/2FA and why use it?
Multi-factor (MFA) or two-factor (2FA) authentication requires a second (or more) factor in addition to password: something you know (password), have (phone, hardware key), or are (biometric).
Why: Passwords can be leaked or guessed; a second factor greatly reduces risk of account takeover. Common methods: TOTP (Google Authenticator, etc.), SMS (less secure), push approval, FIDO2/WebAuthn (hardware keys).
11. What are common security risks in authentication and how to mitigate?
- Weak passwords: Enforce policy or use passkeys; hash with strong algorithm + salt.
- Credential stuffing / reuse: Detect and block; encourage MFA and unique passwords.
- Session fixation / hijacking: Use secure, httpOnly, SameSite cookies; bind session to IP/UA if needed; short session lifetime.
- Token theft: Short-lived access tokens; refresh token rotation; secure storage (no localStorage for refresh in web if possible).
- XSS: Sanitize output; httpOnly cookies so JS can’t read tokens.
- CSRF: SameSite cookies; CSRF tokens for state-changing requests.
12. What is API key authentication and when to use it?
API key: A long-lived secret the client sends (e.g. header X-API-Key or Authorization: ApiKey <key>). Used for:
- Machine-to-machine (server-to-server, scripts, internal services).
- Simple access control for developers or integrations.
Pros: Simple. Cons: No user identity; if leaked, full access until revoked. Rotate keys; restrict by IP or scope when possible; prefer short-lived tokens (e.g. OAuth2 client credentials) for sensitive cases.
13. What is “stateless” authentication?
Stateless means the server does not store session or token state. Each request is validated using only what the client sends (e.g. JWT signature verification). No lookup in DB/Redis for the token.
Pros: Scales horizontally; no shared session store. Cons: Revocation is hard (expiry, blocklist, or short TTL + refresh tokens).
14. How would you implement logout with JWT?
- Client-only: Delete token from client (localStorage/memory). Token remains valid until expiry (weak logout).
- Blocklist: On logout, put token id (e.g.
jti) or the token itself in a blocklist (Redis/DB) and check it on every request. Expire blocklist entries when the token would have expired. - Short-lived access + refresh: Delete refresh token on server on logout; access token expires soon anyway.
Best practice: short-lived access tokens + refresh token stored securely; revoke refresh token on logout; optionally use blocklist for access token if you need immediate invalidation.
15. What is the principle of least privilege in authentication/authorization?
Users and services should get only the minimum permissions they need: minimal roles, scopes, or resource access. Reduces impact of compromised accounts or bugs. Apply it by: role design (e.g. read-only vs admin), scope in OAuth, resource-level checks (e.g. “can this user access this document?”), and regular review of permissions.
Interview angle
- “Authentication versus authorisation?” - authentication establishes identity, authorisation determines permission. They map to 401 and 403 respectively, and conflating them is the most common design confusion in this area.
- “Session or token?” - sessions are server-side state, revocable instantly, and need a shared store across instances. Tokens are stateless and verifiable anywhere but can’t be revoked before expiry. Choose on whether instant revocation or statelessness matters more.
- “How do you store passwords?” - a slow adaptive hash with a per-user salt: bcrypt, scrypt or Argon2. Never a general-purpose hash like SHA-256, which is fast and therefore brute-forceable. See ../25_security/04_password_hashing.md.