Comprehensive coverage of methods, protocols, design principles, and practical mechanisms for proving identity and enforcing permissions across systems. Authentication topics include credential based methods such as passwords and secure password storage, Multi Factor Authentication, one time passwords, certificate based and passwordless authentication, biometric options, federated identity and single sign on using Open Authorization, OpenID Connect and Security Assertion Markup Language, and service identity approaches such as Kerberos and mutual Transport Layer Security. Covers token based and session based patterns including JSON Web Token and session cookies, secure cookie practices, token lifecycle and refresh strategies, token revocation approaches, refresh token design, and secure storage and transport of credentials and tokens. Authorization and access control topics include role based access control, attribute based access control, discretionary and mandatory access control, access control lists and policy based access control, Open Authorization scopes and permission modeling, privilege management and the principle of least privilege, and defenses against privilege escalation and broken access control. The description also addresses cryptographic foundations that underlie identity systems including symmetric and asymmetric cryptography, public key infrastructure and certificate lifecycle management, secure key management and rotation, and encryption in transit and at rest. Common threats and mitigations are covered, such as credential stuffing, brute force attacks, replay attacks, session fixation, cross site request forgery, broken authentication logic, rate limiting, account lockout strategies, secrets management, secure transport, and careful authorization checks. Candidates should be able to design authentication and authorization flows for both user and service identities, evaluate protocol and implementation trade offs, specify secure lifecycle and storage strategies for credentials and tokens, and propose mitigations for common failures and attacks.
MediumTechnical
90 practiced
Explain the differences between an OpenID Connect ID token and an OAuth access token. Describe what each token should contain, who is supposed to consume each one, and common developer mistakes such as using ID tokens as bearer tokens for APIs.
Sample Answer
**Difference — purpose & audience**- ID token: issued by OpenID Connect to authenticate the user to the client (relying party). It proves the user’s identity and is consumed by the client application (browser app/backend that initiated login).- Access token: issued by OAuth 2.0 to authorize access to protected resources (APIs). It is consumed by resource servers (APIs) to enforce scopes/permissions.**What each should contain**- ID token (JWT typical): sub (user id), iss, aud (client_id), exp, iat, nonce (if used), preferred_username/email, maybe profile claims. Designed for the client; contains identity claims.- Access token: scopes/permissions, exp, iss, aud (resource or API), optionally client_id. May be opaque (recommended) or a JWT; only the resource server needs to understand it.**Who consumes**- ID token → client application only.- Access token → API/resource server only.**Common developer mistakes**- Using ID tokens as bearer tokens to call APIs — bad: ID tokens target a client (audience mismatch) and may lack scopes; increases attack surface.- Treating access tokens as user info — access tokens rarely contain full user profile; call userinfo endpoint or use ID token.- Not validating aud/iss/exp/signature or reusing tokens across clients/environments.**Best practices**- Validate signature, aud, iss, exp for both tokens.- Use short-lived access tokens, refresh tokens where appropriate.- Prefer opaque access tokens for APIs and keep identity in ID token or userinfo endpoint.
HardTechnical
51 practiced
Design an approach to map OAuth scopes to application-level fine-grained permissions for APIs. Support hierarchical permissions, resource-level checks (including field-level authorization), policy caching for performance, and explain how to ensure permission updates take effect promptly for existing tokens while maintaining high throughput for API endpoints.
Sample Answer
**Clarify requirements (brief)** Map OAuth scopes -> fine‑grained app permissions; support hierarchical permissions, resource- and field-level checks; policy caching for high throughput; allow permission changes to take effect promptly for existing tokens.**High-level approach**- Use scopes as coarse grants; translate scopes -> permission IDs (e.g., "orders:read" -> [order:list, order:view:id, order:view:line_items.qty]).- Maintain hierarchical permission graph (parent -> children). Precompute transitive closure for fast lookup.- Issue short‑lived access tokens (5–15m) carrying: user_id, client_id, token_issued_at, policy_version (or policy_stamp).- EffectivePermissions = compute_permissions(user_id, client_roles, scopes, policy_version) and cache per (user_id, policy_version).**Core components**- AuthZ Service (PDP): computes effective permissions, holds canonical policies, versioning.- Policy Store: DB + index of hierarchy and field rules.- Cache Layer: Redis for effectivePermissions and policy_versions; supports pub/sub.- API Middleware: reads token, loads cached effectivePermissions, enforces resource+field checks, falls back to PDP on cache miss or for high-sensitivity calls.**Resource & Field-level enforcement**- Represent permissions as resource:action:field (field optional). Example: order:view:line_items.quantity- Serializer/middleware enforces field masks based on permission set before sending response.- For writes, validate permitted fields before applying DB updates.**Policy caching & prompt invalidation**- Versioning: increment global or user-specific policy_version when policies change.- Token includes policy_version at issuance. Cache keys: "perms:{user_id}:{policy_version}".- On update: increment version and publish invalidation event (Redis pub/sub). API nodes subscribe and evict affected cache keys.- To ensure existing tokens reflect changes promptly: - Option A (recommended): short-lived access tokens + refresh tokens. On refresh, new policy_version is issued. - Option B: if immediate enforcement required, API middleware checks a small "revocation" flag or policy_version cutoff in Redis for critical endpoints; if mismatch, force revalidation with PDP.- Combine pub/sub invalidation for near-real-time and short TTL fallback (e.g., 60s) to bound staleness.**Performance & throughput**- Precompute flattened permission bitsets or hashed permission keys for O(1) checks.- Cache effectivePermissions per user+version in Redis as compact bitset or JSON; fetch once per request lifecycle.- Middleware should be async but non-blocking; prefer local LRU + Redis fallback.- Sensitive endpoints skip cache and call PDP or check revocation marker.**Example middleware (Node/Express)**
javascript
// checks permission key like "order:view:line_items.quantity"
async function requirePerm(req, permKey) {
const { userId, policyVersion } = req.token;
const cacheKey = `perms:${userId}:${policyVersion}`;
let perms = await redis.get(cacheKey);
if (!perms) {
perms = await authzService.computePermissions(userId); // stores with version
await redis.set(cacheKey, JSON.stringify(perms), 'EX', 300);
} else perms = JSON.parse(perms);
if (!perms.has(permKey)) throw new Error('Forbidden');
}
**Trade-offs**- Short tokens + refresh = scalable, eventual consistency for policy changes; immediate invalidation requires extra checks.- Pub/sub adds complexity but achieves near real-time invalidation.- Bitsets are fast but less human-readable.**Wrap-up / Best practices**- Keep tokens short-lived and carry policy_version.- Precompute and cache effective permissions keyed by version.- Use pub/sub invalidation plus TTL fallback for prompt updates.- Enforce field-level rules in serialization layer and validate write fields server-side.
MediumTechnical
47 practiced
Stateless JWTs are used as access tokens in your API. Describe three practical strategies to support token revocation (for example after logout or credential compromise): short-lived access tokens, server-side denylist/blacklist checks, and token versioning or revocation fields in user data. For each approach, analyze pros/cons, operational costs, and expected latency impact on each API request.
Sample Answer
**Short-lived access tokens (e.g., 5–15 min)**- Summary: Keep JWT expiry (exp) very short; use refresh tokens to obtain new access tokens.- Pros: Minimal server-side state; compromise window is small; simple to implement.- Cons: Requires refresh-token flow (more client complexity); refresh tokens themselves must be protected and revokable.- Operational cost: Low server state; implement refresh endpoint, secure storage (HTTP-only cookies), monitoring.- Latency impact: None per request beyond normal JWT verification (cryptographic signature check). Refresh exchanges add one extra network call occasionally.**Server-side denylist / blacklist (store revoked jti or token IDs)**- Summary: Store revoked token identifiers (jti) or full tokens in a fast store (Redis). On each request check denylist.- Pros: Immediate revocation; supports specific-token revocation (logout on one device).- Cons: Reintroduces state; must manage expiration of entries to avoid unbounded growth.- Operational cost: Medium — fast cache (Redis), TTL maintenance, replication for HA, potential synchronization across services.- Latency impact: Small extra latency per request (one network hop to Redis); can be mitigated with local caching or bloom filters for high throughput.**Token versioning / revocation field in user data**- Summary: Embed a user-level counter/version in JWT (e.g., token_version). Store token_version in user record; increment on password reset or global logout. On request, compare JWT value to DB/cache.- Pros: Easy to revoke all tokens for a user (compromise recovery) without per-token state; simple semantics.- Cons: Cannot revoke individual tokens selectively; requires a user lookup (DB or cache) per request.- Operational cost: Medium — store version in DB/Redis; maintain cache consistency.- Latency impact: One small lookup to cache/DB per request (can be cached). If cache miss hits DB, higher latency.Practical recommendation for a full‑stack role: combine short TTLs + refresh tokens for low state and risk reduction, add denylist for targeted revocation, and use token_version for bulk/user-wide invalidation. Use Redis for fast checks, secure refresh tokens in HTTP-only cookies, and instrument metrics/TTL cleanup.
EasyTechnical
45 practiced
Describe secure password storage best practices for a web application. Include recommended hashing algorithms (bcrypt, Argon2), the role of salts and optional peppers, how to choose cost/iteration parameters, and considerations and steps for migrating from an insecure hashing scheme (for example migrating from plain SHA1 to Argon2) without forcing all users to reset passwords immediately.
Sample Answer
**Approach / summary**As a full‑stack developer I store passwords as slow, memory‑hard hashes (Argon2 preferred; bcrypt acceptable). Never store plaintext.**Recommended algorithms**- Argon2id (best balance of GPU resistance and side‑channel safety).- bcrypt as fallback for legacy support.- Avoid plain SHA1/SHA256/HMAC-only for passwords.**Salts and peppers**- Per‑password unique salt (cryptographically random, 16+ bytes) stored with the hash.- Optional global pepper: secret kept in app config/SECRETS (not DB). Use pepper to mitigate DB leak; combine before hashing or use as HMAC key.**Choosing cost/iterations**- Pick parameters to make hashing 100–500ms on production hardware; tune memory (Argon2) and iterations (bcrypt) for target latency.- Regularly revisit as hardware changes; run benchmarks in CI.**Migration from insecure scheme**1. Add new column to store scheme/version and new Argon2 hash field.2. On login: verify old SHA1; if valid, rehash plaintext password with Argon2 and write new record (transparent to user).3. For inactive users, force rehash on next successful auth or set a timed policy requiring reset after grace period.4. Batch migrate by attempting background rehash after user provides password (e.g., when they use “forgot password” flow).5. Rotate pepper safely (double‑hash during transition).**Other considerations**- Use slow hashing libs from well‑maintained packages, secure secret storage (KMS/secret manager), rate limiting, and multi‑factor auth.
EasyTechnical
49 practiced
Compare access tokens and refresh tokens in terms of their intended purpose, recommended lifetimes, where they should be stored in a web architecture that includes a browser-based SPA and a backend API, and the primary threat models for each token type.
Sample Answer
**Purpose**- Access token: short-lived bearer token (often JWT) used by SPA to call backend APIs.- Refresh token: long-lived credential used to obtain new access tokens without re-authenticating.**Recommended lifetimes**- Access token: minutes (e.g., 5–15 min).- Refresh token: hours to days (or longer with strict rotation), depends on risk appetite.**Where to store (SPA + backend)**- Access token: keep in memory (JS variable) or short-lived in an HttpOnly cookie if server needs to read it; avoid localStorage/sessionStorage to reduce XSS exposure.- Refresh token: store in an HttpOnly, Secure, SameSite cookie sent to backend for token exchange. Backend validates, rotates, and stores session state (or persistent revocation list).**Primary threat models**- Access token threats: XSS leading to token theft and API misuse; replay on stolen token. Mitigation: short lifetime, audience/scopes, TLS, token binding where possible.- Refresh token threats: theft via CSRF or compromised cookie/store leading to long-lived account takeover. Mitigation: HttpOnly+SameSite cookies, rotation on use, server-side revocation, device fingerprinting, MFA for sensitive flows.Best practices: use TLS, implement refresh token rotation + revocation, scope/minimize privileges, log and monitor anomalous refresh use.
Unlock Full Question Bank
Get access to hundreds of Authentication and Access Control interview questions and detailed answers.