Authentication & Authorization Interview Questions

TL;DR

35+ authentication & authorization interview questions organized by topic. Click "Show Answer" to reveal detailed answers. Covers fundamentals, OAuth 2.0, JWT, SSH, sessions vs tokens, access control, and security best practices.

Short on time? Focus on Fundamentals and OAuth & OIDC — they come up most often in interviews.

Fundamentals

Q: What is the difference between authentication and authorization? Give a real-world analogy.

Authentication (AuthN) verifies identity — "who are you?" Authorization (AuthZ) checks permissions — "what can you do?" Analogy: your boarding pass (authentication — proves you're a passenger) vs your seat assignment (authorization — where you're allowed to sit). Authentication always happens first.

Q: What are the three factors of authentication? Give an example of each.

Something you know: password, PIN. Something you have: phone (TOTP app), hardware key (YubiKey), smart card. Something you are: fingerprint, face scan, iris pattern. True MFA requires at least two different factors.

Q: Why should passwords be hashed with bcrypt instead of SHA-256?

SHA-256 is designed to be fast — attackers can compute billions of hashes per second with GPUs. bcrypt is intentionally slow (configurable work factor), making brute-force attacks impractical. bcrypt also includes built-in salting, preventing rainbow table attacks. Other good choices: Argon2 (recommended by OWASP) and scrypt.

Q: What is a salt in password hashing and why is it necessary?

A salt is random data prepended to the password before hashing. Without salts, identical passwords produce identical hashes — an attacker with a rainbow table (precomputed hash→password database) can crack them instantly. With unique salts, even identical passwords produce different hashes, so each password must be cracked individually.

Q: What's the difference between 401 Unauthorized and 403 Forbidden HTTP status codes?

401 Unauthorized (misnamed): authentication failed — the server doesn't know who you are. Correct action: provide valid credentials. 403 Forbidden: authentication succeeded, but authorization failed — the server knows who you are but you don't have permission. Correct action: request access or use a different account.

Q: What is the principle of least privilege and how does it apply to auth?

Users and services should have only the minimum permissions needed for their task. In auth: grant the narrowest OAuth scopes, use fine-grained RBAC roles, issue short-lived tokens, and default to deny. This limits the blast radius when credentials are compromised.

OAuth 2.0 & OpenID Connect

Q: Explain OAuth 2.0 in simple terms. What problem does it solve?

OAuth 2.0 lets users grant third-party apps limited access to their data without sharing passwords. Example: a calendar app reads your Google contacts. You approve specific scopes ("read contacts only"), Google gives the app a temporary token, and the app never sees your Google password.

Q: What are the four roles in OAuth 2.0?

Resource Owner: the user who owns the data. Client: the app requesting access. Authorization Server: issues tokens after user consent (e.g., accounts.google.com). Resource Server: hosts the protected API (e.g., contacts.google.com).

Q: Walk through the Authorization Code flow with PKCE step by step.

1) Client generates code_verifier (random) + code_challenge (SHA-256 hash). 2) User is redirected to auth server with code_challenge. 3) User logs in and approves scopes. 4) Auth server redirects back with authorization code. 5) Client sends code + code_verifier to token endpoint. 6) Auth server verifies challenge, returns access + refresh + ID tokens. PKCE prevents code interception by requiring proof of the original challenge.

Q: What's the difference between OAuth 2.0 and OpenID Connect?

OAuth 2.0 is for authorization — "what can this app do?" It issues access tokens. OpenID Connect adds authentication — "who is this user?" It adds an ID token (JWT with user claims), a /userinfo endpoint, and standardized scopes (openid, email, profile). OIDC is a layer ON TOP of OAuth 2.0.

Q: Why is the Implicit flow deprecated? What replaced it?

Implicit returns access tokens directly in the URL fragment — visible in browser history, referer headers, and potentially logged. It was replaced by Authorization Code + PKCE, which keeps tokens out of URLs and works securely even in browser-based SPAs.

Q: What are OAuth scopes and why should you request the minimum set?

Scopes define what the token can access (e.g., read:email, write:repo). Minimum scopes: 1) Users are more likely to approve (less scary consent screen), 2) If the token is compromised, the blast radius is limited — an attacker with read:email can't delete repos.

Q: When would you use the Client Credentials grant type?

For machine-to-machine communication with no human user involved — e.g., a cron job calling an API, a microservice authenticating to another service, or a backend worker processing a queue. The app authenticates with its own credentials (client_id + client_secret), not on behalf of a user.

JWT & Token-Based Auth

Q: What are the three parts of a JWT? Describe each.

Header: JSON with alg (signing algorithm) and typ (JWT). Payload: claims — sub (subject), exp (expiry), iat (issued at), plus custom claims. Signature: HMAC or RSA/ECDSA signature of base64(header) + "." + base64(payload) with the secret key. All three are base64url-encoded, joined by dots.

Q: JWTs are "signed but not encrypted." What does this mean practically?

The signature proves integrity (data hasn't been modified) but the payload is just base64-encoded — anyone can decode and read it. Practically: never put passwords, credit cards, or sensitive PII in JWT claims. If you need encryption, use JWE (JSON Web Encryption).

Q: When should you use RS256 vs HS256?

HS256 (symmetric): one shared secret for signing AND verifying. Use when a single service both issues and verifies tokens. RS256 (asymmetric): private key signs, public key verifies. Use when multiple services need to verify tokens — they only need the public key, keeping the signing key secure on the auth server.

Q: Explain the "alg:none" vulnerability. How do you prevent it?

An attacker modifies the JWT header to {"alg":"none"} and removes the signature. Vulnerable libraries accept this and skip verification. Prevention: hardcode the expected algorithm in verification code: algorithms=['RS256']. Never derive the algorithm from the token's header. Use well-maintained libraries that reject "none" by default.

Q: How do access tokens and refresh tokens work together?

Access tokens are short-lived (5-60 min), sent with API requests, and carry authorization claims. Refresh tokens are long-lived (days-months), stored securely (httpOnly cookie), and used to get new access tokens without re-login. When the access token expires, the client sends the refresh token to the auth server to get a fresh access token.

Q: How would you implement JWT revocation in a microservices architecture?

Options: 1) Short-lived tokens (5 min) — revocation happens naturally via expiry. 2) Token blocklist in Redis — store revoked jti claims; only unexpired tokens need tracking, so the list stays small. 3) Token introspection (RFC 7662) — resource servers call the auth server to validate high-risk operations. 4) Refresh token revocation — revoke the refresh token; access token expires soon anyway.

Q: Where should you store JWTs in a browser? Compare the options.

localStorage: vulnerable to XSS (JavaScript can read it). sessionStorage: same as localStorage but clears on tab close. httpOnly cookie: immune to XSS but vulnerable to CSRF (mitigate with SameSite + CSRF tokens). In-memory variable: safest from XSS but lost on refresh. Best practice: access token in memory, refresh token in httpOnly cookie.

SSH & Key-Based Auth

Q: How does SSH key-based authentication work? Walk through the handshake.

1) Client connects and offers its public key. 2) Server checks ~/.ssh/authorized_keys for the key. 3) Server generates a random challenge, encrypts it with the client's public key, sends it. 4) Client decrypts with its private key and returns a hash. 5) Server verifies the hash. The private key never leaves the client and is never sent over the network.

Q: Why should you prefer Ed25519 over RSA for SSH keys?

Ed25519: smaller keys (256 vs 4096 bits), faster operations, resistance to certain side-channel attacks, and deterministic signatures. RSA is only better for compatibility with very old systems. Ed25519 is recommended by OpenSSH and is the default in modern versions.

Q: What's the difference between SSH agent forwarding and ProxyJump? Which is safer?

Agent forwarding (ssh -A): the remote server can use your local agent to authenticate elsewhere — a compromised server can hijack your keys. ProxyJump (ssh -J bastion host): creates a direct tunnel through the bastion — the bastion never accesses your keys or agent. ProxyJump is strictly safer.

Q: A developer's SSH private key is committed to a public repo. What's the incident response?

1) Assume compromised — remove the public key from all authorized_keys immediately. 2) Generate new key pair and deploy. 3) Audit access logs for unauthorized connections. 4) Remove from git history (BFG or git filter-branch). 5) Add id_* to .gitignore and set up pre-commit hooks to prevent future leaks. 6) Review what the key had access to (blast radius).

Q: What happens if ~/.ssh has 777 permissions? Why?

SSH refuses to use the keys — it requires ~/.ssh to be 700 and key files to be 600. This is a security feature: if other users on the system can read your private key, it's no longer "something only you have." SSH enforces this to prevent misconfigured permissions from creating vulnerabilities.

Sessions vs Tokens

Q: Compare session-based and token-based authentication. When would you use each?

Sessions: server stores state (Redis/DB), easy to revoke, needs shared storage at scale, vulnerable to CSRF. Best for: traditional web apps. Tokens: client carries state, any server can verify, hard to revoke before expiry, vulnerable to XSS if stored in localStorage. Best for: APIs, microservices, mobile apps.

Q: How would you handle sessions in a horizontally scaled environment (multiple servers)?

Options: 1) Centralized session store (Redis, Memcached) — all servers read/write from the same store. 2) Sticky sessions (load balancer routes same user to same server) — simple but limits scaling and failover. 3) Switch to tokens (JWTs) — eliminates server-side session storage entirely. Redis-backed sessions are the most common production solution.

Q: What is session fixation and how do you prevent it?

Session fixation: attacker sets a known session ID in the victim's browser (via URL parameter or XSS), then waits for the victim to log in — the session is now authenticated with a known ID. Prevention: regenerate the session ID after login (req.session.regenerate()). The old (attacker-known) session ID becomes invalid.

Q: What security headers should you set on session cookies?

httpOnly: prevents JavaScript access (blocks XSS theft). Secure: only sent over HTTPS. SameSite=Lax or Strict: prevents CSRF (cookie not sent on cross-site requests). Max-Age/Expires: limits cookie lifetime. Path=/: restrict cookie scope. Domain: restrict to your domain only.

Access Control & Authorization Models

Q: Compare RBAC, ABAC, and ACL. When would you use each?

RBAC (Role-Based): users get roles → roles have permissions. Simple, covers 90% of apps. ABAC (Attribute-Based): policies use any attribute (time, location, department, resource owner). Flexible but complex — used in AWS IAM, complex enterprise systems. ACL (Access Control List): per-resource permission lists. Used in file systems and networks. RBAC is the default; use ABAC when RBAC can't express your rules.

Q: What is the difference between authentication and identity federation?

Authentication: verifying credentials locally. Identity federation: trusting an external identity provider (IdP) to authenticate users — e.g., "Login with Google" via OIDC. Your app never sees the password; it trusts Google's assertion of identity. Protocols: SAML (enterprise), OIDC (modern web), and WS-Federation (legacy Microsoft).

Q: What is zero-trust architecture and how does it relate to auth?

Zero-trust: "never trust, always verify" — every request is authenticated and authorized, regardless of network location. No implicit trust for "internal" traffic. Auth implications: continuous verification (not just at login), least-privilege access, microsegmentation, device health checks, and encrypted connections everywhere. Replaces the traditional "castle and moat" perimeter model.

Q: How does API key authentication differ from OAuth token authentication?

API keys: static strings, long-lived, not scoped per-action, represent the app (not a user), simple but risky if leaked. OAuth tokens: short-lived, scoped, represent a user's delegated consent, automatically expire, and can be refreshed. Use API keys for simple service-to-service calls; use OAuth for user-facing applications.

Security Best Practices

Q: What is CSRF and how do you prevent it in a session-based app?

CSRF (Cross-Site Request Forgery): an attacker tricks a logged-in user's browser into making unwanted requests (e.g., transferring money). The browser automatically sends session cookies with the request. Prevention: 1) SameSite cookies (Lax/Strict), 2) CSRF tokens (unique per-form token that attackers can't guess), 3) Check Origin/Referer headers.

Q: How would you securely implement "Remember Me" functionality?

Issue a separate long-lived token (stored in an httpOnly, Secure, SameSite cookie) alongside the session. The token: 1) Is a random, unpredictable value (not the user ID), 2) Maps to a database record with the user ID and expiry, 3) Is single-use (regenerated on each use — token rotation), 4) Has a reasonable expiry (30 days), 5) Can be revoked on password change. Never just extend the session cookie duration.

Q: What is credential stuffing and how do you defend against it?

Credential stuffing: attackers take leaked email/password pairs from one breach and try them on other sites (since people reuse passwords). Defenses: 1) Rate limiting on login endpoints, 2) CAPTCHA after failed attempts, 3) MFA (even if password matches, they need the second factor), 4) Check passwords against breach databases (Have I Been Pwned API), 5) Bot detection (device fingerprinting).

Q: Your team is designing auth for a new microservices platform. What architecture would you recommend?

Centralized auth with distributed verification: 1) Dedicated auth service issues JWTs (RS256) after login. 2) JWKS endpoint publishes public keys. 3) Each microservice verifies JWTs locally using the public key (no cross-service calls). 4) API gateway validates tokens before routing. 5) Short-lived access tokens (5 min) + refresh token rotation. 6) Service-to-service auth via mutual TLS or separate client credentials tokens.

Q: What OWASP security risks are directly related to authentication?

From the OWASP Top 10: A07:2021 - Identification and Authentication Failures: permits brute force, allows weak passwords, has broken credential recovery, stores passwords in plaintext, lacks MFA. Also related: A01 - Broken Access Control (authorization failures), A02 - Cryptographic Failures (weak hashing), and A08 - Software and Data Integrity Failures (JWT manipulation, insecure deserialization).