131 Authentication & Authorization Interview Questions and Answers (2026)

Auth is no longer a side topic you can hand-wave through. As systems scale and breaches make headlines, interviewers now probe deep: token flows, session handling, access control models, and how you'd stop an attack in production. Walk in shaky here and it shows fast—regardless of how strong the rest of your stack is.
This set gives you 131 questions with concise, interview-ready answers—code where it actually helps. It's worked Junior to Mid to Senior, so you build from IAM fundamentals up through OAuth, zero trust, and JWT attacks. Study it end to end and you'll answer like someone who's shipped this, not skimmed it.
Q1.What is the difference between authentication, authorization, and identification?
They are three sequential steps in access control: identification claims who you are, authentication proves it, and authorization decides what you may do.
Identification: Presenting a claimed identity (a username, email, or user ID). No proof yet, just a claim.
Authentication:
Verifying that claim with credentials or factors (password, OTP, biometric, certificate).
Answers "are you really who you say you are?"
Authorization:
Determining permissions for the now-authenticated identity (roles, scopes, policies).
Answers "what are you allowed to do?"
Order matters: you cannot authorize before authenticating, and you cannot authenticate without an identity claim.
Q2.What are the core components of IAM?
IAM?IAM centers on managing digital identities and their access across a system's lifecycle, built from a few interlocking components.
Identity store / directory: The authoritative source of users, groups, and attributes (e.g. LDAP, Active Directory, a database).
Authentication: Verifying identities: passwords, MFA, SSO, and federation protocols.
Authorization: Enforcing what each identity can access via models like RBAC or ABAC and policy engines.
Lifecycle management (provisioning): Creating, updating, and disabling accounts and their entitlements as roles change.
Auditing and governance: Logging access, running access reviews, and proving compliance.
Q3.What is the AAA (Authentication, Authorization, Accounting/Audit) framework in security?
AAA (Authentication, Authorization, Accounting/Audit) framework in security?AAA is a security framework that structures access control into three pillars: Authentication (who you are), Authorization (what you may do), and Accounting/Audit (what you actually did).
Authentication: Confirms identity via credentials or factors before granting entry.
Authorization: Grants or denies specific actions/resources based on the authenticated identity's privileges.
Accounting (Audit):
Records activity: what was accessed, when, and by whom.
Supports billing, forensics, anomaly detection, and compliance reporting.
Common in network access systems: Protocols like RADIUS and TACACS+ implement AAA for device and network login.
Q4.What are the core objectives of Identity and Access Management (IAM)?
IAM)?IAM's core objective is to ensure the right people have the right access to the right resources at the right time, and nothing more.
Confidentiality and least privilege: Grant only the minimum access each identity needs, reducing the attack surface.
Correct authentication: Reliably verify identities so only legitimate users get in.
Accountability: Tie every action to a known identity through logging and audit trails.
Compliance: Meet regulations (GDPR, HIPAA, SOX) with enforceable, reviewable access policies.
Efficiency and user experience: Streamline access via SSO and automated provisioning without weakening security.
Q5.What is Identity and Access Management (IAM)?
IAM)?IAM is the framework of policies, processes, and technologies that manages digital identities and controls their access to resources, ensuring the right entities get appropriate access at the right time.
What it manages: Identities (users, services, devices) and their credentials, roles, and entitlements.
What it does: Authenticates identities, authorizes access, and governs the identity lifecycle.
Common capabilities: Single sign-on (SSO), multi-factor authentication (MFA), role-based access control, and federation.
Goal: Balance security (least privilege, accountability) with usability and compliance.
Q6.Why is Identity and Access Management (IAM) essential in today's era?
IAM) essential in today's era?IAM is essential today because identities have become the primary security perimeter: with cloud, remote work, and countless apps, controlling who accesses what is the main defense against breaches.
Dissolved network perimeter: Cloud and remote work mean access happens from anywhere; "identity is the new perimeter."
Rising threats: Most breaches involve stolen or misused credentials; MFA and least privilege directly reduce this risk.
Scale and complexity: Users, services, and devices sprawl across many systems; centralized IAM keeps access consistent.
Regulatory compliance: Laws like GDPR, HIPAA, and SOX demand provable access controls and audit trails.
Productivity: SSO and automated provisioning cut friction and support costs while staying secure.
Zero Trust enablement: Continuous verification of every request depends on strong identity as the foundation.
Q7.What are the common authentication factors (something you know, something you have, something you are)?
Authentication factors are the categories of evidence used to prove identity, traditionally grouped into three types; combining factors from different categories yields multi-factor authentication (MFA).
Something you know (knowledge):
Secrets the user recalls: passwords, PINs, security answers.
Weakest factor alone: phishable, guessable, and reusable across sites.
Something you have (possession):
A physical or digital token: a phone running an authenticator app, a hardware key (FIDO2/YubiKey), a smart card.
Time-based codes (TOTP) or cryptographic challenges prove possession.
Something you are (inherence):
Biometrics: fingerprint, face, iris, voice.
Convenient but not secret and not revocable: you can't reissue a fingerprint.
Emerging/contextual factors: Somewhere you are (geolocation, IP) and behavioral signals are sometimes used as adaptive factors.
Key point: true MFA mixes categories: Two passwords are still one factor; a password plus a hardware key is two, so a single compromised credential isn't enough.
Q8.What is a claim in the context of identity, and how does it relate to a principal or subject?
A claim is a statement about a subject asserted by an issuer, such as "email is alice@example.com" or "role is admin". The subject (also called the principal) is the entity the claims describe, and a collection of claims about that subject forms its identity.
Claim = name/value assertion:
Example: sub=1234, email=alice@x.com, role=admin.
A claim is only as trustworthy as its issuer: you trust it because you trust who signed it.
Subject / principal:
The authenticated entity (user, service, device) that claims describe, usually identified by the sub claim.
"Principal" is the runtime security context your app builds from those claims.
Relationship:
Authentication verifies the subject; the resulting token carries claims; authorization then makes decisions by reading those claims.
In practice: a JWT's payload is a bag of claims about one subject, signed by the issuer.
Q9.Explain the principle of least privilege. Why is it a foundational security concept?
The principle of least privilege (PoLP) says every user, service, or process should have only the minimum permissions needed to do its job, and no more. It's foundational because it shrinks the blast radius: if a credential or component is compromised, the attacker inherits only that narrow set of rights.
Core idea:
Grant exactly what's required, for exactly as long as it's required (scope + time).
Applies to people, service accounts, tokens, and processes alike.
Why it's foundational:
Limits blast radius: a stolen token or compromised microservice can only reach what it was granted.
Contains lateral movement: attackers can't pivot to unrelated systems.
Reduces accidental damage from bugs or human error.
How it shows up in practice:
Scoped OAuth tokens, narrowly-scoped IAM roles, read-only DB users, per-service credentials.
Just-in-time / time-bound elevation instead of standing admin access.
Related principle: Pairs with separation of duties: no single identity should hold enough privilege to abuse a whole workflow alone.
Q10.Explain the deny by default principle in authorization.
Deny by default means access is refused unless there is an explicit rule granting it: the absence of a matching permission is treated as "no". It's the secure default because it fails closed, so forgetting to define a rule locks people out rather than accidentally exposing a resource.
Whitelist, not blacklist:
You enumerate what's allowed; everything else is implicitly denied.
Blacklisting (deny specific things, allow the rest) inevitably misses cases.
Fail closed:
On errors, missing config, or unmatched routes, the safe outcome is denial.
A new endpoint added without an auth rule should be inaccessible, not open.
Precedence of explicit deny: In many policy engines an explicit deny overrides any allow, so grants can't accidentally re-open something.
Practical effect: Requires deliberate, auditable grants and makes over-exposure a visible mistake rather than a silent one.
Q11.Why should authorization logic never be enforced solely on the client side?
Client-side code runs on hardware the user fully controls, so any check there can be inspected, bypassed, or forged. Client-side authorization is only a UX convenience; the authoritative decision must always be enforced on the server, which is the trusted boundary the attacker cannot alter.
The client is untrusted:
Users can edit JavaScript, modify local state, and craft raw HTTP requests with tools like curl or Postman, skipping the UI entirely.
Hiding a button doesn't disable the underlying endpoint.
Client checks are informational, not enforcement:
Fine to hide/disable UI elements for a smoother experience.
But the same decision must be re-made server-side on every request.
Common failure: Broken access control (OWASP #1): endpoints that trust a client-sent role, a hidden field, or an isAdmin flag are trivially bypassed.
Rule: Authenticate and authorize on the server for every resource and action; treat all client input, including identity claims, as attacker-controlled until verified.
Q12.Why do we hash passwords instead of encrypting them for storage?
We hash passwords because hashing is one-way: we only ever need to verify a password, not recover it. Encryption is reversible, which means a key exists that can turn every stored password back into plaintext, creating a single catastrophic point of failure if that key is compromised.
Hashing is one-way:
At login you hash the input and compare digests; you never need the original.
A leaked hash database still forces attackers to crack each password.
Encryption is reversible:
It requires a key; whoever holds the key can decrypt every password at once.
Key management becomes the weak link (insider access, key leak, backups).
Principle: You should never be able to tell a user their own password, only reset it, which proves you're not storing recoverable secrets.
Q13.What is a password encoder and why is it mandatory?
A password encoder is a component that transforms a plaintext password into a one-way, salted hash for storage and later verification: it is mandatory because storing or comparing plaintext passwords is catastrophic if the database leaks.
One-way transformation: Uses a cryptographic hash so the original password cannot be recovered from stored data.
Salting: A unique random salt per password defeats precomputed rainbow tables and ensures identical passwords hash differently.
Deliberately slow / work-factored: Adaptive algorithms add a tunable cost so brute-forcing leaked hashes is expensive.
Why mandatory: If plaintext (or fast unsalted hashes like MD5) leaks, every account is instantly compromised, plus password reuse exposes users elsewhere.
Q14.What is a JSON Web Token (JWT)? Describe its structure (header, payload, signature) and the purpose of each part.
JWT)? Describe its structure (header, payload, signature) and the purpose of each part.A JWT is a compact, URL-safe token that carries claims as JSON, digitally signed so its integrity can be verified. It has three Base64URL-encoded parts joined by dots: header, payload, and signature.
Header: JSON metadata describing the token: the signing algorithm (alg) and type (typ), sometimes a key id (kid).
Payload:
The claims: statements about the subject plus standard fields like exp and sub.
Only encoded, not encrypted: never put secrets here.
Signature:
Computed over the encoded header and payload with a secret (HMAC) or private key (RSA/ECDSA).
Lets the receiver verify the token wasn't tampered with and came from a trusted issuer.
Q15.What is the role of the payload in a JWT?
payload in a JWT?The payload is the middle section of a JWT that carries the claims: the actual JSON statements about the subject and the token itself. It's what the receiving service reads to make authentication and authorization decisions.
What it holds:
Registered claims (sub, exp, iss, aud) for standard, interoperable meaning.
Custom (private) claims like role or tenant_id for app-specific data.
Why it enables statelessness: The server reads identity and permissions straight from the token, avoiding a session lookup.
Key caveat: It's only Base64URL-encoded, not encrypted: readable by anyone, so keep it free of secrets and reasonably small.
Q16.Why should you avoid putting sensitive data in a JWT payload?
JWT payload?A JWT payload is only encoded (Base64URL), not encrypted, so anyone who holds the token can read every claim: signing proves integrity, not confidentiality.
The payload is readable by anyone: Base64URL is trivially decoded (e.g. paste into jwt.io), so PII, passwords, or secrets are exposed.
Signatures protect integrity, not secrecy: A signature (HMAC/RSA) lets you detect tampering but does nothing to hide the contents.
Tokens live in many places: They sit in browser storage, logs, proxies, and caches, widening the leak surface.
What to do instead:
Store only non-sensitive identifiers (e.g. a user id or opaque reference) and look up sensitive data server-side.
If you truly must carry secrets in a token, use JWE (encrypted JWT).
Q17.What is the main difference between OAuth 2.0 (for authorization) and OpenID Connect (for authentication)?
OAuth 2.0 (for authorization) and OpenID Connect (for authentication)?OAuth 2.0 authorizes access (what an app is allowed to do with your data), while OpenID Connect authenticates the user (proving who they are). OIDC is a layer on top of OAuth that adds the identity piece OAuth deliberately leaves out.
OAuth 2.0: authorization:
Issues an access token used to call APIs.
The token is meant for the resource server; it says nothing reliable about the user's identity to the client.
OIDC: authentication: Issues an ID Token (a signed JWT) meant for the client, proving the user logged in and who they are.
Common mistake: Using an access token as proof of login ("pseudo-authentication") is insecure: it wasn't issued for the client and can be replayed. Use the ID Token for identity.
Analogy: OAuth is a valet key (permission to do something); OIDC is showing your ID (proof of who you are).
Q18.What is user consent in OAuth, and what role does the consent screen play?
OAuth, and what role does the consent screen play?User consent is the resource owner explicitly authorizing a client application to access a specific set of scopes on their behalf. The consent screen is where the authorization server shows the user which app is requesting access and exactly what it wants, so the grant is informed and deliberate rather than silent.
What consent establishes:
The user (resource owner), not the app, authorizes access to their protected resources.
It ties a specific client to a specific set of scope values (e.g. read:email).
Role of the consent screen:
Displays the client identity and requested scopes in human-readable terms so the user can make an informed choice.
Lets the user approve or deny, and the authorization server records the decision.
Practical behavior:
Consent is often remembered, so repeat authorizations skip the screen unless new scopes are requested.
First-party or trusted apps may have consent auto-approved by policy.
It's a defense against over-privileged access: the user gates what the token can do.
Q19.Can you explain how OTP (One-Time Password) is used for verification in an authentication flow?
OTP (One-Time Password) is used for verification in an authentication flow?An OTP is a short code valid for a single use (or short window) that proves the user controls a channel or device at login time. The server generates or derives the code, delivers or expects it, and verifies a match before granting access.
Typical flow:
User submits primary credentials (or requests a code).
Server generates an OTP and delivers it (SMS/email) or the user reads it from an authenticator app (TOTP).
User enters the code; server compares against the expected value within a validity window.
On match, server marks it used/consumed and completes authentication.
Two generation models:
Delivered OTP: server creates a random code and sends it over a side channel.
Derived OTP: both sides compute it from a shared secret (HOTP counter or TOTP time), so nothing is transmitted.
Security essentials:
Short expiry, single use (invalidate after verification), and rate-limiting/lockout to stop brute force.
Remember: OTPs prove channel control but are phishable, so they're a factor, not full anti-phishing.
Q20.Describe the use cases and limitations of API keys for authentication.
An API key is a static, opaque string a client sends to identify itself, typically for server-to-server or public API access. It's simple to issue and use but is a weak credential: it identifies the caller without proving much, and offers no built-in user context or expiry.
Good use cases:
Machine-to-machine or backend integrations where a full OAuth flow is overkill.
Identifying and rate-limiting/metering an application or project (e.g. usage quotas, billing).
Read-only or low-sensitivity public APIs.
Limitations:
It's a bearer secret: anyone who obtains it has full access, so leakage (in code, logs, URLs) is dangerous.
Usually long-lived with no built-in expiry or standardized rotation.
Identifies an app, not a user, and carries no fine-grained scopes by default.
Best practices: Send in a header (not query string), transmit over TLS, store hashed, scope narrowly, and support rotation/revocation.
Q21.What is authentication in API design?
Authentication in API design is the process of verifying who is making a request: confirming the identity of the calling user or service before the API acts on it. It answers "who are you?" and is distinct from authorization, which answers "what are you allowed to do?"
What it establishes: A verified identity (a user, service, or application) that later authorization decisions build on.
Common mechanisms:
Bearer tokens / JWTs sent in the Authorization header.
API keys for app identification.
OAuth 2.0 / OIDC for delegated and user identity.
mTLS for service-to-service identity.
Design principles: Prefer stateless, standard credentials; always over TLS; keep authentication separate from authorization logic.
Q22.What is the difference between a 401 Unauthorized and a 403 Forbidden response?
401 Unauthorized and a 403 Forbidden response?A 401 Unauthorized means the request is not authenticated (identity is missing or invalid), while a 403 Forbidden means the request is authenticated but the identity lacks permission for the resource.
401 = who are you?:
No credentials, expired token, or bad signature; fixable by authenticating.
Should include a WWW-Authenticate header to challenge the client.
403 = you can't do this:
Identity is known and valid, but authorization rules deny it (wrong role/scope/ownership).
Re-authenticating won't help; the permission itself is the issue.
Naming caveat:
The name "Unauthorized" is historically misleading: it really means unauthenticated.
For privacy, some APIs return 404 instead of 403 to avoid revealing a resource's existence.
Q23.What is the difference between a brute-force attack and a dictionary attack, and what are common prevention methods for each?
Both try many password guesses against an account, but a brute-force attack systematically tries every possible combination (all characters up to some length), while a dictionary attack tries a curated list of likely passwords (common words, leaked passwords, patterns). Dictionary attacks are far more efficient because real users pick predictable passwords.
Brute-force:
Exhaustive: aaaa, aaab, ... guaranteed to find the password eventually but cost grows exponentially with length.
Defended by password length/complexity, slow hashing (bcrypt, argon2), and rate limiting.
Dictionary:
Tries known-likely values, often from breach corpora (e.g. rockyou).
Defended by blocking known-breached/common passwords (e.g. Have I Been Pwned checks) and encouraging passphrases.
Shared defenses:
Per-account rate limiting/lockout, MFA, and slow salted hashes make both economically impractical.
Salting defeats precomputed tables (rainbow tables), forcing per-hash work.
Q24.What is user provisioning and de-provisioning in Identity and Access Management?
Provisioning is creating and granting a user's accounts and access rights; de-provisioning is revoking them. Together they manage the access side of the identity lifecycle.
Provisioning:
On joining or role change: create accounts and assign entitlements (often role-based).
Can be automated from an HR system as the authoritative source ("joiner" events).
De-provisioning:
On leaving or role change: disable accounts and remove access promptly ("leaver" events).
Critical for security: orphaned or lingering accounts are a common breach vector.
Re-provisioning / "mover" events: When someone changes departments, add new access and strip old to avoid privilege creep.
Automation matters: Standards like SCIM sync users across apps so provisioning stays consistent and timely.
Q25.What is the difference between authentication and identity management?
Authentication is a single act (verifying a credential at login), while identity management is the broader ongoing discipline of creating, maintaining, and governing identities throughout their lifecycle.
Authentication:
A point-in-time check: does this credential prove this identity?
One capability within identity management.
Identity management:
Manages the identity itself: creation, attributes, roles, provisioning, and eventual deactivation.
Provides the identity store that authentication verifies against.
Relationship: Authentication is a runtime event; identity management is the lifecycle framework that makes reliable authentication possible.
Q26.What is coarse-grained vs. fine-grained authorization? Provide examples.
Coarse-grained authorization makes decisions at a broad level (can this role access this feature at all?), while fine-grained authorization decides at the level of individual resources, records, or fields (can this specific user edit this specific document?). Most real systems combine both.
Coarse-grained:
Based on role, group, or scope: "admins can access the billing module."
Cheap to evaluate, often enforced at the route/endpoint or API-gateway level.
Example: a token scope orders:read lets any holder call the orders endpoints.
Fine-grained:
Considers the specific resource and its attributes: ownership, relationship, state, or individual field.
Example: "a user may edit only orders they created and only while status is draft."
Often needs data-level context, so it lives closer to the domain logic (ABAC, ReBAC like Google Zanzibar).
How they work together:
Coarse check gates the door (right role/scope); fine-grained check verifies rights over the exact object.
Passing the coarse check is never sufficient: a user with orders:read still shouldn't read another customer's order.
Q27.What is separation of duties, and how does it complement the principle of least privilege?
Separation of duties (SoD) splits a sensitive process across two or more people or roles so no single actor can complete it alone: it prevents fraud and error by requiring collusion. It complements least privilege by controlling not just how much access one identity has, but how conflicting privileges are distributed across identities.
Core idea of SoD:
No one person controls a whole critical transaction (e.g. one employee requests a payment, another approves it).
Reduces insider fraud and honest mistakes by forcing a second party into the loop.
Least privilege recap: Each identity gets only the permissions it needs, for only as long as it needs them.
How they complement each other:
Least privilege limits the blast radius of one account; SoD ensures two dangerous privileges never land in the same account.
Example: least privilege says a developer shouldn't touch production; SoD says the person who writes code shouldn't also be the one who deploys and approves it.
Practical enforcement: Toxic-combination rules (mutually exclusive roles), maker/checker workflows, and periodic access reviews to catch violations.
Q28.What is defense in depth, and how does it apply to authentication and authorization?
Defense in depth is layering multiple independent security controls so that if one fails or is bypassed, others still protect the system. For auth, it means never relying on a single gate: authentication, authorization, transport security, and monitoring reinforce each other.
Core principle: Assume any single control can be compromised, so no one layer is a single point of failure.
Layers in authentication:
Strong password hashing (bcrypt, argon2), plus MFA, plus rate limiting and anomaly detection on login.
Short-lived tokens and rotation limit the value of a stolen credential.
Layers in authorization:
Check permissions at the API gateway and again in the service, and enforce row/field-level rules at the data layer.
Client-side checks are for UX only; the server re-verifies every decision.
Supporting layers: TLS in transit, encryption at rest, network segmentation, and audit logging so breaches are detected and contained.
Payoff: An attacker must defeat several distinct controls, buying time for detection and reducing blast radius.
Q29.Explain Role-Based Access Control (RBAC). What are its advantages and limitations, such as role explosion?
RBAC). What are its advantages and limitations, such as role explosion?RBAC grants permissions to roles rather than to individual users, and then assigns users to roles: access is determined by what role you hold, not who you are. It's simple and auditable but can become unwieldy when fine-grained or contextual rules force you to create ever more roles (role explosion).
How it works:
Permissions attach to roles (e.g. editor can create/edit articles); users are members of one or more roles.
Often hierarchical: admin inherits all of editor's permissions.
Advantages:
Easy to reason about and audit: "who can do X?" becomes "which roles have X?"
Low admin overhead for onboarding: assign a role instead of dozens of individual permissions.
Maps cleanly to organizational job functions.
Limitations:
Role explosion: encoding fine distinctions (region, department, seniority) multiplies roles combinatorially like editor-emea-finance.
Poor at contextual/dynamic rules (time of day, resource ownership, request attributes).
Hard to express "can edit only their own records" without per-resource logic.
Mitigations: Role hierarchies, permission grouping, and combining RBAC with a few ABAC-style attribute checks for context.
Q30.What is the difference between role-based access control (RBAC) and attribute-based access control (ABAC), and when would you use each?
RBAC) and attribute-based access control (ABAC), and when would you use each?RBAC decides access from the roles a user holds; ABAC decides from a policy that evaluates attributes of the user, resource, action, and environment. RBAC is simpler and easier to audit for stable job functions; ABAC is more expressive for fine-grained, contextual, or dynamic rules.
RBAC:
Access = function of assigned roles; static and coarse-grained.
Easy to audit and administer, but struggles with context and suffers role explosion.
ABAC:
Access = policy over attributes: subject (department, clearance), resource (owner, sensitivity), action, environment (time, IP).
Example: "allow if user.department == resource.department and time is business hours."
Highly flexible but harder to author, test, and audit ("who can access X?" requires evaluating policies).
When to use each:
RBAC: stable org structure, clear job functions, need for simple auditing.
ABAC: fine-grained, data-dependent, or context-aware rules (multi-tenant isolation, ownership, regulatory constraints).
Common in practice: hybrid: roles for the broad strokes plus attribute checks for context.
Q31.How would you implement role-based access control (RBAC)?
RBAC)?Implement RBAC by modeling users, roles, and permissions as separate entities with many-to-many links, then checking at request time whether any of the caller's roles grants the required permission. Keep the enforcement server-side and centralize the check so it's consistent across endpoints.
Data model:
Tables: users, roles, permissions, plus join tables user_roles and role_permissions.
Assign permissions to roles, users to roles: avoid attaching permissions directly to users.
Enforcement:
At each protected action, resolve the user's roles to a permission set and require the specific permission (not just a role name).
Centralize with middleware/decorators so checks aren't duplicated or forgotten.
Carrying roles: Put roles/permissions in a verified token claim (e.g. JWT) or look them up per request; balance token size vs. freshness.
Operational concerns:
Support role hierarchy/inheritance, audit assignments, and cache-then-invalidate to reflect revocations quickly.
Default deny: absence of a matching permission means access denied.
Q32.What are the different types of access control models (RBAC, ABAC, ACLs, MAC, DAC)? Explain their core principles.
RBAC, ABAC, ACLs, MAC, DAC)? Explain their core principles.These are the classic access-control models, differing mainly in who sets the rules and what the decision is based on. DAC lets owners set access; MAC enforces system-wide labels; RBAC uses roles; ABAC uses attribute policies; and ACLs are a mechanism listing permissions per resource.
DAC (Discretionary Access Control):
The resource owner grants/revokes access at their discretion (e.g. Unix file permissions, sharing a doc).
Flexible but prone to over-sharing and privilege leakage.
MAC (Mandatory Access Control):
A central authority assigns labels/clearances (e.g. secret, top-secret); users can't override them.
Rigid and high-assurance: used in military/government (e.g. SELinux, Bell-LaPadula).
RBAC (Role-Based): Permissions grouped into roles; users get access via role membership. Simple and auditable.
ABAC (Attribute-Based): Policies evaluate subject/resource/action/environment attributes for fine-grained, contextual decisions.
ACLs (Access Control Lists):
A per-resource list of (principal, allowed actions); a mechanism often used to implement DAC.
Precise per object but hard to manage at scale.
Key distinction: DAC vs. MAC is about who controls policy (owner vs. system); RBAC/ABAC are about how permissions are structured; ACLs are a storage/enforcement mechanism.
Q33.Explain the concept of claims-based authorization.
Claims-based authorization makes decisions from claims: assertions about an identity (like role, email, department, or subscription tier) that are carried in a verified token issued by a trusted authority. Instead of the app looking up who a user is, it trusts and inspects the signed claims presented with the request.
What a claim is:
A key/value statement about the subject (e.g. role=admin, email_verified=true) vouched for by the issuer.
Delivered in tokens like a JWT and validated via signature and issuer/audience checks.
How authorization uses them:
Policies assert required claims ("must have claim scope=orders:write") rather than hardcoding user identities.
Roles become just one kind of claim, so RBAC and finer rules coexist naturally.
Why it's useful:
Decouples apps from the identity store: the issuer (IdP) owns identity, apps just consume claims.
Enables SSO and federation across services that trust the same issuer.
Caveats:
Always verify the token's signature, issuer, audience, and expiry before trusting claims.
Claims are a snapshot at issue time: stale claims persist until the token expires unless you support revocation.
Q34.What is the difference between discretionary (DAC) and mandatory (MAC) access control?
DAC) and mandatory (MAC) access control?DAC lets resource owners decide who gets access (permissions set at the owner's discretion), while MAC enforces access centrally through system-wide policy and security labels that users cannot override.
Discretionary Access Control (DAC):
The owner of an object grants or revokes access to others (e.g. Unix file permissions, ACLs).
Flexible but riskier: a user can pass on their access, so privileges can leak or spread.
Mandatory Access Control (MAC):
A central authority defines policy; access is decided by comparing subject clearance against object classification labels (e.g. Secret, Top Secret).
Users (even owners) cannot change the rules, enforced by systems like SELinux and used in military/high-security contexts.
Core distinction:
DAC = discretion sits with the owner; MAC = discretion sits with system policy.
MAC trades flexibility for stronger, non-bypassable control.
Q35.Explain password hashing, salting, and peppering. Why are adaptive hashing algorithms like bcrypt, scrypt, and Argon2 preferred over fast hashes like MD5 or SHA-1 for passwords?
bcrypt, scrypt, and Argon2 preferred over fast hashes like MD5 or SHA-1 for passwords?Hashing turns a password into a fixed, one-way digest; salting adds a unique random value per password so identical passwords hash differently; peppering adds a secret value stored separately from the database. Adaptive algorithms are preferred because they are deliberately slow and tunable, making large-scale guessing expensive, whereas fast hashes let attackers try billions of guesses per second.
Salt (per-password, stored with the hash):
Random and unique per user, so two users with the same password get different hashes.
Defeats precomputed attacks (rainbow tables) and forces attackers to crack each hash individually.
Pepper (secret, stored separately): A site-wide secret kept outside the DB (app config or HSM); a stolen database alone can't be cracked without it.
Why adaptive hashes beat fast ones:
MD5/SHA-1 are built to be fast, ideal for GPUs doing billions of guesses per second.
bcrypt, scrypt, and Argon2 have a tunable cost so hashing stays deliberately slow.
scrypt and Argon2 are also memory-hard, resisting GPU/ASIC parallelism; Argon2id is the modern recommendation.
Q36.What is a work factor or cost factor in password hashing, and why is it important?
The work factor (cost factor) is a tunable parameter in adaptive hashing that controls how much computation (and sometimes memory) each hash requires. It matters because it lets you keep password hashing deliberately slow for attackers as hardware improves, without changing the algorithm.
What it controls:
bcrypt uses a cost that doubles the number of iterations per increment (exponential).
Argon2/scrypt tune time (iterations), memory, and parallelism.
Why it matters:
Higher cost multiplies the attacker's guessing time linearly (or worse), shrinking their throughput.
You raise it over time as CPUs/GPUs get faster to keep the same defensive margin.
Tuning trade-off:
Too high hurts your own login latency and can enable DoS; aim for a target like roughly 100 to 500 ms per hash on your hardware.
The cost is stored in the hash string, so verification knows which parameters to use and you can upgrade gradually on next login.
Q37.Which password encoder would you use and why?
I would use a memory-hard adaptive algorithm, ideally Argon2id, or bcrypt as a well-supported default: both are salted, slow, and tunable, unlike fast general-purpose hashes.
Argon2id: Modern winner of the Password Hashing Competition; memory-hard, so it resists GPU/ASIC cracking. Preferred for new systems.
bcrypt: Battle-tested, widely available, adjustable work factor; a safe default when Argon2 tuning isn't available. Note its ~72-byte input limit.
scrypt: Also memory-hard; acceptable, but Argon2id is generally preferred today.
Avoid: Plain MD5, SHA-256 and similar fast hashes: they're built for speed, which is exactly wrong for passwords.
Practical tip: Use a delegating encoder (e.g. Spring's DelegatingPasswordEncoder) so you can upgrade algorithms over time without breaking existing hashes.
Q38.What are the arguments for and against mandatory periodic password rotation policies?
Mandatory periodic rotation forces users to change passwords on a fixed schedule; modern guidance (NIST) advises against it because it tends to weaken security in practice, favoring rotation only on evidence of compromise.
Arguments for:
Limits the useful lifetime of an undetected stolen credential.
Historically satisfies compliance/audit checkboxes.
Arguments against:
Users respond with predictable, weaker variants (Password1 then Password2), reducing entropy.
Encourages writing passwords down and reuse fatigue.
Frequent changes don't stop an attacker who acts immediately after theft.
Modern consensus: Rotate only when there's evidence of compromise; instead invest in length, breached-password checks, and MFA.
Q39.What is password entropy, and how does it relate to password strength requirements?
Password entropy is a measure (in bits) of how unpredictable a password is: it quantifies how many guesses an attacker needs on average, so higher entropy means stronger resistance to brute force.
How it's calculated: Roughly log2(N^L) where N is the symbol pool size and L the length: each extra bit doubles the guessing effort.
Length beats complexity: Increasing length adds far more entropy than adding a symbol class, which is why long passphrases outperform short complex passwords.
The caveat: Theoretical entropy assumes randomness; human-chosen passwords have low effective entropy because attackers guess patterns and dictionaries first.
Relation to requirements: Justifies minimum-length rules and passphrases over rigid composition rules that add little real entropy.
Q40.What is breached-password (credential) checking, and why is it recommended over complex composition rules?
Breached-password checking compares a new password against known leaked-credential datasets and rejects any that appear there: it targets the passwords attackers actually try, which composition rules fail to address.
How it works: Check against a breach corpus (e.g. Have I Been Pwned) using a k-anonymity range query so the full password/hash is never sent.
Why it beats composition rules:
A password can satisfy every complexity rule yet still be common and already leaked (P@ssw0rd1).
Attackers use credential-stuffing lists, so blocking known-breached values stops the most likely attack directly.
Usability: Rigid rules frustrate users and push predictable patterns; breach checks reject only genuinely risky choices.
NIST alignment: Recommended over mandatory complexity and rotation in current guidance.
Q41.How is JWT used for authentication and authorization?
JWT used for authentication and authorization?A JWT (JSON Web Token) is a signed, self-contained token: after login the server issues it, the client sends it on each request, and the server verifies the signature to authenticate the user and reads its claims to authorize actions, all without a server-side session lookup.
Structure: Three base64url parts: header (algorithm), payload (claims), and signature.
Authentication: Server signs claims like sub and exp; on each request it re-verifies the signature to prove the token is genuine and unexpired.
Authorization: Roles/scopes in the payload (e.g. roles, scope) let the server decide access without hitting a database.
Stateless benefit: No shared session store needed, which scales well across services.
Key trade-offs:
Payload is signed, not encrypted (readable by anyone), and tokens can't be easily revoked, so use short expiries plus refresh tokens.
Always pin the algorithm to reject the alg: none and key-confusion attacks.
Q42.Discuss the security implications and trade-offs of storing JWTs on the client side, such as in HTTP-only cookies vs. local storage.
JWTs on the client side, such as in HTTP-only cookies vs. local storage.The core trade-off is XSS exposure versus CSRF exposure: localStorage is easy but readable by any JavaScript (XSS steals the token), while an HTTP-only cookie hides the token from scripts but is sent automatically (needing CSRF defenses). HTTP-only cookies are generally the safer default.
localStorage / sessionStorage:
Pros: simple to use, no CSRF risk (not sent automatically), works cleanly across domains for APIs.
Cons: any XSS can read it and exfiltrate the token; this is the dominant risk.
HTTP-only cookie:
Pros: HttpOnly blocks JavaScript access, mitigating token theft via XSS; add Secure and SameSite.
Cons: sent automatically, so it's vulnerable to CSRF unless you use SameSite and/or anti-CSRF tokens.
Recommendation: Prefer HTTP-only, Secure, SameSite cookies with CSRF protection; keep access tokens short-lived and store refresh tokens especially carefully.
Underlying truth: Neither storage saves you if XSS exists, so a strong Content-Security-Policy and input handling matter more than the storage choice alone.
Q43.What is the difference between an access token, refresh token, and ID token in the context of OAuth 2.0 and OpenID Connect?
OAuth 2.0 and OpenID Connect?Each token has a distinct job: the access token grants API access, the refresh token gets new access tokens without re-login, and the ID token proves who the user is. OAuth 2.0 defines access and refresh tokens (authorization); OpenID Connect adds the ID token (authentication).
Access token:
Short-lived credential the client sends to a resource server (API) to authorize requests, usually as a Bearer token.
Meant for the API, not the client: the client should treat it as opaque.
Refresh token:
Long-lived credential used only against the authorization server to mint new access tokens when they expire.
Sensitive: stored securely, often rotated, and can be revoked to end a session.
ID token:
An OIDC-specific JWT that describes the authenticated user (claims like sub, name, email).
Intended for the client to consume, not to call APIs with.
Common mistake: using an ID token to call an API, or inspecting an access token's contents. Match each token to its audience.
Q44.What are the standard claims in a JWT (iss, sub, aud, exp, iat, nbf, jti) and what is the purpose of each?
JWT (iss, sub, aud, exp, iat, nbf, jti) and what is the purpose of each?These are the IANA-registered standard claims defined by the JWT spec. They're optional but interoperable, letting any validator understand identity, timing, and scope without custom agreement.
iss (issuer): who created and signed the token; validators check it against a trusted issuer.
sub (subject): the principal the token is about, typically a user id.
aud (audience): the intended recipient(s); a service should reject tokens not addressed to it.
exp (expiration): time after which the token is invalid; enforces short lifetimes.
iat (issued at): when the token was created; useful for age checks.
nbf (not before): time before which the token must not be accepted.
jti (JWT ID): a unique identifier for the token, used for replay prevention or targeted revocation via a denylist.
Q45.Is a JWT encrypted or encoded? Explain the difference and its security implications.
JWT encrypted or encoded? Explain the difference and its security implications.A standard JWT is encoded and signed, not encrypted: anyone holding it can read the payload by Base64URL-decoding it. The signature guarantees integrity and authenticity, not confidentiality.
Encoding vs encryption:
Encoding (Base64URL) is a reversible format change with no key: trivially decodable.
Encryption requires a key to read the content; a signed-only JWT provides none.
Security implications:
Never store secrets (passwords, PII you must protect) in the payload: it's effectively public to the bearer.
Always send JWTs over TLS to prevent interception.
When you need confidentiality: Use JWE (JSON Web Encryption) to encrypt the payload; the common signed JWT is technically a JWS.
Q46.Explain the concept of token introspection and when it would be used.
Token introspection is an OAuth 2.0 mechanism (RFC 7662) where a resource server asks the authorization server whether a token is currently valid and what metadata it carries. It's how you validate opaque tokens and get real-time state that a self-contained JWT can't provide.
How it works:
The resource server POSTs the token to the /introspect endpoint (authenticated as a client).
The response returns active plus claims like scope, sub, exp.
When to use it:
Opaque (reference) access tokens that carry no readable claims.
When you need up-to-the-second revocation status rather than trusting exp.
Trade-off: A network call per validation (unlike local JWT verification); often cached briefly to reduce load.
Q47.Explain the concept of token revocation and why it's important.
Token revocation is the act of invalidating a token before its natural expiry so it can no longer be used. It's important because tokens get leaked, devices get lost, and users log out or lose permissions, and you need a way to cut off access immediately rather than waiting for expiration.
Why it matters:
Compromise response: a stolen token must be killable on demand.
Logout and session end: users expect signing out to actually end access.
Permission changes: revoke when a user is deactivated or roles change.
How it's done:
OAuth exposes a /revoke endpoint (RFC 7009), typically for refresh tokens.
Stateful backends maintain a denylist or track valid sessions.
The tension: Stateless JWTs resist revocation, so most designs pair short-lived access tokens with revocable refresh tokens.
Q48.How do you handle token expiration in JWT?
JWT?You enforce expiration by setting a short-lived exp claim at issue time and rejecting any token whose exp is in the past during validation: this bounds the damage window if a token leaks.
Set expiration at issue:
The exp claim (a Unix timestamp) is embedded and covered by the signature, so it can't be tampered with.
Keep access tokens short (minutes), since they're hard to revoke early.
Validate on every request:
The verifier checks exp (and often nbf/iat) and rejects expired tokens with a 401.
Allow a small clock-skew leeway (e.g. 30–60s) so minor time drift doesn't cause false rejections.
Recover gracefully: On expiry the client uses a longer-lived refresh token to obtain a new access token, avoiding re-login.
Remember the trade-off: Expiration is not revocation: a stolen token is valid until exp. Short lifetimes plus a revocation/denylist strategy close that gap.
Q49.How can you refresh a JWT token?
JWT token?You refresh by pairing a short-lived access token with a longer-lived refresh token: when the access token expires, the client sends the refresh token to a dedicated endpoint, which validates it and issues a fresh access token (and often a new refresh token).
Two-token model:
Access token: short-lived, sent on every API call.
Refresh token: long-lived, stored securely (e.g. an HttpOnly cookie), used only against the token endpoint.
The refresh flow:
Access token expires and the API returns 401.
Client POSTs the refresh token to the auth server.
Server verifies it (signature, expiry, not revoked) and returns a new access token.
Refresh token rotation: Issue a new refresh token on each use and invalidate the old one; if an already-used token reappears, treat it as theft and revoke the whole chain.
Why refresh tokens can be revoked: They're typically opaque and tracked server-side, so logout or compromise can invalidate them, unlike a self-contained access token.
Q50.Explain OAuth 2.0. What problem does it solve, and what are its core roles (resource owner, client, authorization server, resource server)?
OAuth 2.0. What problem does it solve, and what are its core roles (resource owner, client, authorization server, resource server)?OAuth 2.0 is a delegated authorization framework: it lets a user grant an application limited access to their resources on another service without sharing their password. It solves the "password anti-pattern" of handing your credentials to third-party apps.
The problem it solves: Instead of giving an app your Google password, you grant it a scoped, revocable access token so it can only do what you allowed.
Resource Owner: The user who owns the data and grants access.
Client: The application requesting access on the user's behalf (web app, SPA, mobile app).
Authorization Server: Authenticates the resource owner, gets consent, and issues tokens (e.g. Google's OAuth server).
Resource Server: The API that holds the protected resources and accepts the access token.
Key point: OAuth is about authorization (what an app may do), not authentication (proving who a user is): that gap is what OIDC fills.
Q51.Explain OpenID Connect (OIDC). How does it build on OAuth 2.0, and what additional functionality does it provide (ID Token, UserInfo Endpoint)?
OpenID Connect (OIDC). How does it build on OAuth 2.0, and what additional functionality does it provide (ID Token, UserInfo Endpoint)?OpenID Connect is a thin identity layer on top of OAuth 2.0: it reuses the same flows but adds a standardized way to authenticate the user and learn who they are, via the ID Token and the UserInfo endpoint.
Builds on OAuth 2.0: Same Authorization Code + PKCE flow, but the client adds the openid scope to request identity.
ID Token:
A signed JWT with identity claims (sub, iss, aud, exp, iat) that the client validates to know the user is authenticated.
This is the piece plain OAuth lacks: proof of authentication in a verifiable, tamper-evident token.
UserInfo endpoint: An OAuth-protected API returning profile claims (name, email, picture) when called with the access token, for details not in the ID Token.
Discovery and standardization: Standard metadata at /.well-known/openid-configuration and a JWKS endpoint let clients auto-discover endpoints and signing keys.
Bottom line: OAuth answers "can this app access X?"; OIDC also answers "who is this user, and when did they log in?"
Q52.What are OAuth scopes, and how do they limit the permissions granted to applications?
OAuth scopes, and how do they limit the permissions granted to applications?Scopes are named permission strings a client requests and the user consents to, bounding exactly what an access token can do on the resource server. They implement least privilege for delegated access.
How they work:
The client asks for scopes (e.g. read:contacts, write:calendar) at authorization time.
The user sees and approves them on the consent screen; the granted scopes are bound to the issued token.
The resource server checks the token's scopes before serving each endpoint.
What they limit: Scope of data (which resources) and action (read vs write), so a compromised token has bounded blast radius.
Important distinctions:
Scopes are coarse, app-facing consent, not a replacement for fine-grained, per-user authorization (roles/ownership) enforced server-side.
The server may grant fewer scopes than requested, so clients must handle a reduced set.
Q53.What is the purpose of the state parameter in the OAuth authorization code flow?
state parameter in the OAuth authorization code flow?The state parameter is an opaque, unguessable value the client generates before redirecting and verifies when the callback returns. Its main job is CSRF protection for the authorization flow, binding the response to the request that started it.
How it protects against CSRF:
Client stores state (e.g. in the session) and sends it in the authorize request.
The authorization server echoes it back unchanged on the redirect.
If the returned state doesn't match, the client rejects the callback, blocking an attacker from injecting their own authorization code.
Requirements: Must be random, unpredictable, and tied to the user's session, not a fixed constant.
Secondary use: Can carry app context (e.g. the page to return to), but security relies on the matching check, not the payload.
Relation to PKCE: They solve different problems: state prevents CSRF, PKCE prevents code interception; use both.
Q54.Why is OAuth 2.0 often misused for authentication, and what problems does that cause?
OAuth 2.0 often misused for authentication, and what problems does that cause?OAuth 2.0 is an authorization (delegated access) protocol, not an authentication one, but developers reuse it to "log in" by treating possession of an access token as proof of identity. That confusion leads to real vulnerabilities because an access token says nothing reliable about who the user is or who the token was issued to.
OAuth answers "can this app access this resource?" not "who is this user?": An access_token is a bearer credential for an API, opaque to the client, with no defined identity claims.
The core misuse: treating token possession as authentication: Fetching a "userinfo"-style endpoint with a token proves access, not that the current user authenticated to your app.
Resulting problems:
Token substitution / confused deputy: a token issued for one app can be replayed to another, letting an attacker log in as someone else.
No audience or nonce binding, so there's no guarantee the token was minted for your client or your session.
The fix: OpenID Connect: OIDC layers an id_token (a signed JWT) on top of OAuth with identity claims, aud, iss, and nonce so you can verify who authenticated and for whom.
Q55.What is machine-to-machine authentication, and how does the client-credentials flow support it?
client-credentials flow support it?Machine-to-machine (M2M) authentication is when a service authenticates as itself, with no human user involved, to call another service. OAuth's client-credentials flow supports this: the client presents its own credentials directly to the token endpoint and receives an access token representing the application, not a user.
The scenario: Backend jobs, cron tasks, or service-to-service API calls where there's no user to redirect or consent.
How client credentials works:
The client sends grant_type=client_credentials with its client_id and client_secret (or a signed assertion / mTLS) to the token endpoint.
The authorization server returns an access_token whose subject is the application itself.
No user, no browser, no refresh_token: the client just requests a new token when it expires.
Security notes:
Only for confidential clients that can protect a secret.
Scopes limit what the machine can do; prefer short-lived tokens and rotate credentials.
Q56.What is the purpose of the nonce in OpenID Connect?
nonce in OpenID Connect?The nonce in OpenID Connect is a random value the client generates and sends in the authentication request, which the authorization server embeds into the issued ID token. Its purpose is to bind the token to the specific request/session, preventing replay attacks where a stolen or reused ID token is injected into a different login.
How it flows:
Client generates a unique nonce, stores it in the user's session, and includes it in the authorization request.
The provider copies it into the nonce claim of the signed id_token.
On receipt, the client checks the token's nonce matches the stored value.
What it protects against: ID token replay/injection: an attacker can't reuse a captured token because its nonce won't match a fresh session.
How it differs from state: nonce binds the ID token to the session (replay protection); state binds the redirect callback to the request (CSRF protection).
Q57.What is discovery in OpenID Connect, and how does the well-known configuration endpoint help clients?
OpenID Connect, and how does the well-known configuration endpoint help clients?Discovery lets an OIDC client learn how to talk to an identity provider automatically, by fetching a standard JSON metadata document from a well-known URL instead of hardcoding endpoints and keys.
The discovery document:
Served at /.well-known/openid-configuration relative to the issuer.
A JSON object describing the provider's capabilities and URLs.
Key fields:
issuer, authorization_endpoint, token_endpoint, userinfo_endpoint.
jwks_uri: where clients fetch public keys to verify ID token signatures.
Supported scopes, response types, and signing algorithms.
Why it helps clients:
No manual configuration: point the client at the issuer and it self-configures.
Handles key rotation: clients refetch jwks_uri to get new signing keys without redeployment.
Q58.Explain the concept of Single Sign-On (SSO) and how protocols like SAML or OIDC facilitate it.
SAML or OIDC facilitate it.SSO lets a user authenticate once with a central identity provider and then access many applications without logging in again: the apps trust the provider rather than managing their own credentials.
Core idea:
A central Identity Provider (IdP) authenticates the user and issues a token or assertion.
Applications (relying parties / service providers) trust that token instead of prompting for credentials again.
How SAML facilitates it:
XML-based assertions passed via browser redirects/POST between IdP and SP.
Common in enterprise web apps.
How OIDC facilitates it:
Built on OAuth 2.0, issues a signed JSON id_token (JWT) proving authentication.
Popular for modern web, mobile, and API-driven apps.
Benefits:
Fewer passwords, better UX, centralized policy (MFA, session revocation).
Trade-off: the IdP becomes a single point of failure and a high-value attack target.
Q59.What's the difference between JWT, OAuth, and SAML?
JWT, OAuth, and SAML?They operate at different layers: JWT is a token format, OAuth is an authorization framework, and SAML is a full authentication/SSO protocol. They are often combined rather than compared as alternatives.
JWT (JSON Web Token):
A compact, signed data format (a container), not a protocol.
Carries claims and can be verified without a database lookup; used as access or ID tokens.
OAuth 2.0:
An authorization framework: delegates access to resources ("let app X call API Y on my behalf").
About authorization, not authentication; its tokens are often JWTs.
SAML:
An XML-based standard for authentication and SSO, mostly enterprise.
Exchanges signed assertions between IdP and SP.
How they relate: OIDC = OAuth 2.0 + authentication, using JWTs, filling the same SSO role as SAML for modern apps.
Q60.Explain the conceptual flow of Kerberos authentication. What are its main components (KDC, AS, TGS)?
KDC, AS, TGS)?Kerberos is a ticket-based authentication protocol where a trusted third party (the KDC) issues time-limited tickets so clients and services can authenticate without sending passwords over the network. It relies on symmetric encryption and mutual trust in the KDC.
Main components:
KDC (Key Distribution Center): the trusted server, containing the AS and TGS.
AS (Authentication Server): verifies the user and issues a Ticket-Granting Ticket (TGT).
TGS (Ticket-Granting Service): exchanges a valid TGT for service-specific tickets.
Conceptual flow:
Client authenticates to the AS; AS returns a TGT encrypted with the TGS key plus a session key.
To reach a service, client presents the TGT to the TGS and requests a service ticket.
TGS issues a service ticket encrypted with the target service's key.
Client presents the service ticket to the service, which decrypts and grants access (optionally mutual auth).
Why tickets:
Passwords never traverse the network; tickets are short-lived, limiting replay.
Requires reasonably synced clocks (timestamps prevent replay).
Q61.What is LDAP and how is it used as an identity store, particularly with Active Directory?
LDAP and how is it used as an identity store, particularly with Active Directory?LDAP (Lightweight Directory Access Protocol) is a protocol for querying and modifying a hierarchical directory of entries (users, groups, computers). It is commonly used as a centralized identity store, and Active Directory is Microsoft's directory service that speaks LDAP.
What LDAP is:
A protocol, not the database itself, for accessing a directory tree.
Entries are identified by a Distinguished Name (DN), e.g. cn=jdoe,ou=users,dc=corp,dc=com.
How it authenticates:
A "bind" operation authenticates a user by their DN and password.
Apps often do a search to find the DN, then bind to verify credentials.
As an identity store:
Central source of users, group memberships, and attributes for authorization.
Queried with filters, e.g. (&(objectClass=user)(memberOf=...)).
Relationship to Active Directory:
AD exposes an LDAP interface but adds Kerberos, group policy, and DNS integration.
Apps commonly authenticate against AD via LDAP(S), while native Windows uses Kerberos.
Q62.Explain how SAML assertions work and the roles of the Identity Provider and Service Provider.
SAML assertions work and the roles of the Identity Provider and Service Provider.A SAML assertion is a signed XML statement issued by the Identity Provider vouching that a user is authenticated; the Service Provider consumes it to grant access. The IdP proves identity, the SP trusts and relies on that proof.
Roles:
Identity Provider (IdP): authenticates the user and issues signed assertions.
Service Provider (SP): the application the user wants; validates the assertion and creates a session.
Assertion contents:
Authentication statement: who was authenticated and how/when.
Attribute statement: user attributes like email, roles, groups.
Conditions: validity window and intended audience (the SP).
Trust and integrity:
Signed with the IdP's private key; SP verifies with the IdP's public certificate exchanged during metadata setup.
The SP checks signature, audience, and expiry before trusting it.
Delivery: Typically posted through the user's browser (HTTP POST binding) to the SP's Assertion Consumer Service.
Q63.What is the difference between a centralized identity provider and per-application authentication? What are the trade-offs?
A centralized identity provider authenticates users once for many applications, while per-application authentication has each app manage its own credentials and sessions. Centralizing improves security and UX at the cost of a single point of failure and integration effort.
Centralized IdP (e.g. SSO via OIDC/SAML):
Pros: one set of credentials, consistent MFA/password policy, central audit and instant deprovisioning, one place to harden.
Cons: single point of failure (IdP down = everything down), a breach is blast-radius-wide, upfront integration complexity.
Per-application authentication:
Pros: apps are independent and self-contained, no external dependency, simple for a single small system.
Cons: credential sprawl, inconsistent security, painful offboarding (must revoke in each app), poor user experience.
Key trade-off framing:
Centralization concentrates both control and risk: you get uniform policy but must invest heavily in the IdP's availability and security.
Rule of thumb: as the number of apps and users grows, centralized identity almost always wins.
Q64.What is social login, and what are the risks of relying on a third-party identity provider?
Social login lets users authenticate to your app using an existing account at a provider like Google, Apple, or Facebook, typically via OpenID Connect. It removes password management for users but couples your access to a third party you don't control.
How it works: The provider acts as the IdP; your app receives an ID token with verified claims (subject, email) and creates/links a local account.
Benefits: No passwords to store, lower signup friction, inherits the provider's MFA and security investment.
Risks of depending on a third party:
Availability/lock-in: if the provider is down or bans your app, users can't log in.
Account takeover cascade: a compromised social account compromises your app too.
Privacy and data control: the provider sees where users log in, and you depend on the claims they choose to share.
Email-based linking pitfalls: trusting an unverified email claim can allow account hijacking; always use the stable sub identifier.
Mitigation: Support multiple providers plus a fallback login, and let users link/unlink identities to avoid single-provider lock-in.
Q65.Explain Multi-Factor Authentication (MFA). What are its common types such as TOTP, push-based, and biometrics, and their trade-offs?
TOTP, push-based, and biometrics, and their trade-offs?MFA requires two or more independent factors from different categories: something you know (password), something you have (phone, security key), and something you are (biometric). Combining categories means stealing one factor isn't enough to log in.
TOTP (authenticator app codes):
A shared secret generates a rotating 6-digit code; works offline.
Trade-off: strong and cheap, but phishable (user can type the code into a fake site) and secret can be copied at setup.
Push-based (approve on phone):
Server sends a prompt to a trusted device; user taps approve.
Trade-off: great UX, but vulnerable to MFA fatigue/bombing unless number-matching is used.
SMS/email OTP: Easiest to adopt, but weakest: SIM-swap, SS7 interception, and phishing all apply.
Biometrics (fingerprint, face):
Convenient and hard to phish remotely; usually a local unlock for a device-bound key rather than sent to the server.
Trade-off: not revocable if compromised, and false-accept/reject rates matter.
Hardware security keys (FIDO2/WebAuthn): Phishing-resistant because the credential is bound to the site origin; the strongest common option.
Q66.What are Passkeys / WebAuthn / FIDO2, and what problems do they solve compared to traditional password-based authentication?
WebAuthn / FIDO2, and what problems do they solve compared to traditional password-based authentication?Passkeys are a passwordless credential built on the WebAuthn API and FIDO2 standards: a public/private key pair per site where the private key never leaves the user's device. They replace passwords with public-key cryptography, eliminating phishing and credential-database breaches.
The stack:
FIDO2 = the overall standard, made of WebAuthn (browser/JS API) and CTAP (talks to authenticators like phones and keys).
A passkey is a discoverable FIDO2 credential, often synced across a user's devices via their platform (Apple/Google/Microsoft).
How it authenticates:
The server sends a random challenge; the device signs it with the private key (unlocked by biometric/PIN) and returns the signature.
The signature is bound to the site's origin, so it can't be replayed on a phishing site.
Problems it solves vs passwords:
Phishing-resistant: origin binding stops credential reuse on fake sites.
No shared secret: the server stores only a public key, so a breach leaks nothing usable.
No reuse or weak passwords, and no separate MFA step (possession + biometric are built in).
Caveat: account recovery: Device loss and cross-ecosystem sync remain the hard parts; you still need a recovery path.
Q67.What is MFA fatigue/bombing, and how can it be mitigated?
MFA fatigue (also called MFA bombing or prompt spamming) is an attack where an adversary who already has the victim's password triggers a flood of push-approval requests, hoping the user eventually taps approve out of annoyance or confusion. It exploits the human, not the protocol.
Why it works: Simple push approvals ask only yes/no, so a fatigued or careless user can approve an attacker's login.
Mitigations:
Number matching: user must type a code shown on the login screen, so a blind tap can't succeed.
Show context: display location, app, and IP in the prompt so anomalies are obvious.
Rate-limit and throttle prompts; block or alert after repeated denials.
Use phishing-resistant factors (FIDO2/passkeys) that have no approve button to spam.
Root cause: The password was already compromised, so also enforce strong/unique passwords and detect credential leaks.
Q68.What is the difference between TOTP and HOTP one-time passwords?
TOTP and HOTP one-time passwords?Both derive a one-time code from a shared secret using HMAC, but HOTP is counter-based (event-driven) while TOTP is time-based. TOTP is essentially HOTP where the moving factor is the current time interval.
HOTP (RFC 4226):
Code = HMAC(secret, counter); the counter increments each time a code is generated.
Code stays valid until used, so client and server counters can drift out of sync (needs a look-ahead window).
TOTP (RFC 6238):
Counter = floor(current_time / step), usually a 30-second step; code auto-expires each window.
Requires roughly synced clocks; servers often accept the adjacent window for clock skew.
Practical takeaway:
TOTP is what authenticator apps (Google Authenticator, Authy) use because time-limited codes reduce exposure and avoid counter drift.
HOTP suits offline hardware tokens with no clock.
Q69.Why is SMS-based OTP considered a weaker second factor, and what attacks target it?
SMS OTP is weak because the code travels over a channel not designed for security and often bound to something (a phone number) that can be transferred or intercepted, so possession of the phone isn't reliably proven.
SIM swapping: An attacker social-engineers the carrier into porting the victim's number to a new SIM, then receives all OTPs.
SS7 / network interception: Weaknesses in the telco signaling protocol (SS7) let attackers reroute or read SMS in transit.
Real-time phishing: OTP is not phishing-resistant: a proxy site prompts the user for the code and relays it instantly to the real service.
Device and delivery exposure: Codes show on lock screens, sync to other devices, or land in malware-infected phones.
Better alternatives: TOTP authenticator apps avoid the SMS channel; WebAuthn/passkeys add phishing resistance via origin binding.
Still better than nothing: NIST discourages SMS but it beats password-only for casual accounts.
Q70.How do magic-link and one-time-code passwordless flows work, and what are their trade-offs?
Both are passwordless flows that prove control of an email/phone: a magic link is a clickable URL carrying a signed token, while a one-time code is a short value the user copies back into the app. Both replace the password with a possession-of-inbox proof.
Magic-link flow:
User enters email; server generates a single-use, short-lived, signed token and emails a link containing it.
Clicking the link hits a verification endpoint that validates the token and starts a session.
One-time-code flow: Same start, but a numeric/alphanumeric code is emailed/texted and typed back, keeping login on the original device.
Shared requirements: Tokens must be single-use, expiring, rate-limited, and unguessable (high entropy) to resist brute force and replay.
Trade-offs:
Magic link: smooth on the same device, but breaks when the link opens in a different browser/device than the login started.
OTP code: works across devices and avoids link-context issues, but adds typing friction and is prone to real-time phishing relay.
Both inherit email/SMS security: only as strong as the delivery channel and account.
Q71.How does biometric authentication work as a factor, and what do false-accept and false-reject rates mean?
Biometric authentication is an "inherence" factor: it verifies a physical trait (fingerprint, face) by comparing a live sample to a stored template. Because biometrics are probabilistic, systems set a matching threshold, and false-accept and false-reject rates describe the two error types that threshold produces.
How it works:
Enrollment captures the trait and derives a mathematical template (never a raw image).
At login, a fresh sample is scored for similarity; if it clears the threshold, it matches.
False Accept Rate (FAR): Frequency an impostor is wrongly accepted: the security-critical error.
False Reject Rate (FRR): Frequency a legitimate user is wrongly rejected: the usability-critical error.
The tuning trade-off: Raising the threshold lowers FAR but raises FRR; they move in opposite directions (crossover point is the EER).
Key security point: Biometrics are not secrets and can't be revoked, so they should unlock a local credential (e.g. a passkey on the device), not be sent to a server as the credential itself.
Q72.What is the role of recovery codes in MFA, and how should they be stored and handled?
Recovery codes are a pre-generated set of single-use backup secrets that let a user regain access when their primary second factor is lost or unavailable, preventing permanent lockout.
Purpose: A break-glass fallback for a lost phone/authenticator, avoiding costly manual account recovery.
Generation and display: Issued as a batch of high-entropy codes shown to the user exactly once, with a prompt to store them offline.
Server-side storage: Stored hashed (like passwords), never in plaintext, so a DB leak doesn't expose usable codes.
Usage rules: Each code is single-use and invalidated after redemption; support regenerating the whole set (which revokes the old batch).
Security posture: They are a bypass of MFA, so treat them as high-value secrets: rate-limit attempts and alert the user when one is used.
Q73.Compare and contrast session-based authentication and token-based authentication such as JWT. Discuss their statefulness, scalability, and security trade-offs.
JWT. Discuss their statefulness, scalability, and security trade-offs.Session-based auth stores state on the server and hands the client an opaque session ID (usually in a cookie); token-based auth like JWT is self-contained, carrying signed claims the server validates without a lookup. The core trade-off is server state and easy revocation versus statelessness and easy horizontal scaling.
Statefulness:
Sessions: server keeps a session store; the cookie is just a reference ID.
JWT: server keeps nothing; the token itself holds claims verified by signature.
Scalability:
Sessions need shared/sticky storage (e.g. Redis) across nodes, an extra dependency.
JWTs scale cleanly: any node validates the signature locally, ideal for stateless APIs and microservices.
Revocation:
Sessions: delete server-side to log out instantly.
JWTs: valid until expiry, so revocation needs a denylist or short lifetimes plus refresh tokens (which reintroduces state).
Security trade-offs:
Cookie sessions face CSRF (mitigate with SameSite and CSRF tokens) but keep no secret in JS.
JWTs in JS-accessible storage face XSS token theft; never put sensitive data in the payload since it's only signed, not encrypted.
Rule of thumb: Classic web app with a single backend: sessions. Distributed/stateless APIs or third-party access: tokens.
Q74.Explain session fixation and session hijacking attacks. What are common mitigations?
Both attacks let an adversary take over a user's authenticated session, but by different means: session fixation forces the victim to use a session ID the attacker already knows, while session hijacking steals a legitimate ID after it's issued.
Session fixation: Attacker plants a known session ID (via URL or a set cookie) before login; when the victim authenticates on that same ID, the attacker is now logged in too.
Session hijacking: Attacker captures a valid ID after login, via XSS, packet sniffing on unencrypted traffic, or a leaked token.
Mitigations:
Regenerate the session ID on every privilege change, especially right after login (kills fixation).
Set cookies with HttpOnly (blocks JS theft), Secure (HTTPS only), and SameSite.
Enforce TLS everywhere so IDs can't be sniffed in transit.
Expire sessions (idle and absolute timeouts) and bind loosely to context, and prevent XSS to protect the token at rest in the browser.
Q75.How can CSRF attacks impact authentication (against session cookies), and what are the primary defenses (SameSite cookies, anti-CSRF tokens)?
SameSite cookies, anti-CSRF tokens)?CSRF (Cross-Site Request Forgery) abuses the browser's habit of auto-attaching session cookies: a malicious site tricks the victim's browser into sending an authenticated request to your app, so the server executes it as the logged-in user. It matters specifically for cookie-based auth because the credential travels automatically.
Why cookies are vulnerable:
The browser sends session cookies on any request to your domain, even one initiated by an attacker's page (a form POST or image tag).
Token-in-header schemes (e.g. Authorization: Bearer) are not auto-sent, so they are largely immune.
Defense: SameSite cookies:
SameSite=Lax (a good default) blocks the cookie on cross-site subrequests but allows top-level navigations.
SameSite=Strict blocks all cross-site sends; None requires Secure and reopens CSRF risk.
Defense: anti-CSRF tokens:
Synchronizer token: server issues a random token tied to the session, the form/JS echoes it, and the server rejects requests missing or mismatching it. The attacker's site can't read it (same-origin policy).
Double-submit cookie: token stored in a cookie and also sent in a header; server checks they match, needing no server state.
Best practice: combine SameSite + tokens, and treat state-changing operations as POST/PUT/DELETE (never GET).
Q76.What are the Secure, HttpOnly, and SameSite attributes for cookies, and how do they enhance security for session management?
Secure, HttpOnly, and SameSite attributes for cookies, and how do they enhance security for session management?These three cookie attributes harden session cookies against interception, theft, and cross-site abuse. Together they ensure the cookie only travels over TLS, can't be read by scripts, and isn't sent on cross-site requests.
Secure: The cookie is only sent over HTTPS, preventing exposure on plaintext HTTP where a network attacker could sniff it.
HttpOnly: JavaScript can't read the cookie via document.cookie, so an XSS flaw can't directly steal the session ID.
SameSite: Controls whether the cookie is sent on cross-site requests: Strict, Lax, or None. This is the primary CSRF mitigation.
For session management, set all three: Secure; HttpOnly; SameSite=Lax (or Strict), and scope with Path and Domain.
Q77.What is the difference between idle (inactivity) timeout and absolute session timeout, and why use both?
An idle timeout expires a session after a period of no activity, while an absolute timeout expires it a fixed time after login regardless of activity. Using both limits the damage window from a stolen session without letting any session live indefinitely.
Idle (inactivity) timeout:
Resets on each request; if the user goes quiet (e.g. 15-30 min), the session dies.
Protects abandoned sessions on shared or unlocked devices.
Absolute timeout:
A hard cap from authentication time (e.g. 8-12 hours) that never extends, forcing full re-authentication.
Bounds the lifetime of a hijacked session even if the attacker keeps it active.
Why both: Idle alone can be kept alive forever by a busy attacker; absolute alone lets an idle-but-valid session sit exploitable. Combined, they cover both cases.
Q78.How does server-side session invalidation on logout work, and why is stateless logout harder?
Server-side logout works because the session's authority lives on the server: deleting the session record (or marking it revoked) instantly makes the cookie's session ID meaningless. Stateless tokens like JWTs are harder because they're self-contained and trusted until expiry, so there's nothing central to delete.
Server-side session invalidation:
On logout, the server removes the session from its store (DB, Redis) and clears the client cookie.
The next request presents an ID that no longer maps to anything, so it's rejected immediately.
Why stateless logout is harder:
A JWT is validated by signature and exp alone, so a copy stays valid until it expires even after "logout."
You can't un-issue it without reintroducing server state.
Mitigations for stateless tokens:
Short-lived access tokens plus a revocable refresh token stored server-side.
A denylist/blocklist of revoked token IDs (jti) checked on each request, which sacrifices pure statelessness.
Q79.Explain the API Gateway authentication pattern and its benefits.
In the API Gateway authentication pattern, a single gateway sits in front of all backend services and centralizes authentication: it validates credentials/tokens on incoming requests before routing them, so individual services don't each reimplement auth. The gateway typically forwards a verified identity to downstream services.
How it works:
The gateway verifies the token/API key/session, rejects unauthenticated requests early, and passes trusted identity headers (or a re-signed internal token) to services.
Can also handle token exchange, rate limiting, and TLS termination.
Benefits:
Centralization: one place to enforce and audit auth policy, reducing duplication and inconsistency.
Simpler services: backends focus on business logic and trust the gateway's verification.
Consistent cross-cutting concerns: logging, throttling, and credential rotation in one layer.
Caveats: The gateway is a single point of failure and a high-value target; secure the internal network (e.g. mTLS) so services aren't blindly trusting spoofed headers (defense in depth / zero trust).
Q80.What is the role of authentication and authorization middleware, and why is their order important?
Authentication middleware establishes who the caller is; authorization middleware decides what they may do. Order matters because you cannot authorize an identity you haven't yet established, so authentication must run first.
Authentication middleware:
Parses credentials (token, cookie, header), validates them, and attaches a principal/identity to the request context.
It answers "who are you?" but makes no access decision.
Authorization middleware:
Reads that established identity and its roles/scopes to allow or deny the specific route or action.
It answers "are you allowed?"
Why order is critical:
Authorization depends on the identity authentication populates; reversing them means authorizing against an empty/unknown principal.
Correct sequencing also yields correct responses: no identity gives 401, valid identity without permission gives 403.
Q81.Can you describe the process of authentication and authorization in Web APIs?
In a Web API the client first proves its identity (authentication), the server issues or accepts a credential, and then on each request the server verifies that credential and checks whether the identity is permitted to perform the requested operation (authorization).
Client obtains a credential: User logs in (or a service authenticates) and receives a token such as a JWT or an API key.
Credential sent per request: Typically in the Authorization header (e.g. Bearer <token>); APIs are usually stateless, so every request carries it.
Server authenticates the request: Validates the token signature/expiry or looks up the session; establishes the principal. Failure gives 401.
Server authorizes the action: Checks roles, scopes, or ownership against the requested resource/operation. Denial gives 403.
Request proceeds: Handler runs and returns data; use HTTPS throughout so credentials aren't exposed in transit.
Q82.Explain the HTTP authentication schemes — Basic, Digest, and Bearer — and how the Authorization header is used with each.
Authorization header is used with each.All three are HTTP authentication schemes that place credentials in the Authorization header as Authorization: <scheme> <credentials>; they differ in how the credentials are formed and how secure they are.
Basic:
Sends base64(username:password) as Authorization: Basic ....
Base64 is encoding, not encryption, so it must only be used over HTTPS.
Digest:
Sends a hash (MD5) of credentials combined with a server nonce, so the raw password never crosses the wire.
Resists replay via the nonce but is dated and rarely used in modern APIs.
Bearer:
Sends a token (often OAuth2/JWT) as Authorization: Bearer <token>.
"Bearer" means whoever holds the token can use it, so it must stay secret and go over HTTPS; it's the dominant scheme for APIs.
Q83.What is the purpose of the WWW-Authenticate header and the 401 challenge in HTTP authentication?
WWW-Authenticate header and the 401 challenge in HTTP authentication?When a request lacks valid credentials, the server returns 401 Unauthorized with a WWW-Authenticate header: this pair is the HTTP "challenge" that tells the client authentication is required and which scheme(s) to use to authenticate.
The 401 challenge: Signals "you are not authenticated"; per spec a 401 response must include WWW-Authenticate.
The WWW-Authenticate header:
Names the accepted scheme and parameters, e.g. WWW-Authenticate: Basic realm="api" or Bearer error="invalid_token".
The realm labels the protection space so the client knows which credentials apply.
Client reaction: A browser can show a login prompt; a programmatic client resends with an Authorization header matching the challenged scheme.
Q84.What is Zero Trust Architecture? Explain its core principles, such as 'never trust, always verify' and continuous verification.
Zero Trust Architecture (ZTA) is a security model that assumes no implicit trust based on network location: every access request must be authenticated, authorized, and continuously validated regardless of whether it originates inside or outside the network.
Never trust, always verify: Being on the corporate network grants nothing; identity, device, and context are checked on every request.
Continuous verification: Trust is not a one-time login event; sessions are re-evaluated as risk signals change (new location, device posture, anomalous behavior).
Least privilege access: Grant the minimum permission needed, just-in-time and just-enough, to limit what any compromised identity can reach.
Assume breach: Design as if attackers are already inside: segment, encrypt everywhere, and log to contain blast radius.
Policy-driven enforcement: A policy engine (PDP) makes decisions from many signals and a policy enforcement point (PEP) applies them at each access.
Q85.How does Zero Trust differ from traditional perimeter-based security?
Traditional perimeter security trusts anything inside the network wall (the "castle and moat"), while Zero Trust removes implicit trust and verifies every request individually no matter where it comes from.
Trust boundary:
Perimeter: a hard outer edge (firewall/VPN); once inside, users move freely.
Zero Trust: trust is per-request and per-resource, there is no trusted interior.
Lateral movement: Perimeter models let a breached host roam widely inside; Zero Trust uses micro-segmentation to block that.
Verification: Perimeter verifies mostly at the edge, once; Zero Trust verifies continuously with identity and context.
Fit for modern IT: Cloud, SaaS, and remote work dissolve the perimeter, so "inside vs outside" is no longer meaningful; Zero Trust centers on identity, which travels with the user.
Q86.How is identity important in Zero Trust Architecture?
Identity is the foundation and new perimeter of Zero Trust: since network location is no longer trusted, every access decision hinges on strongly verifying who (or what) is making the request and their associated context.
Identity is the new perimeter: With no trusted network, authenticated identity becomes the primary control point for access.
Strong authentication: MFA and phishing-resistant methods (FIDO2/passkeys) raise assurance that the identity is genuine.
Covers non-human identities too: Services, workloads, and devices each get a verifiable identity (e.g. SPIFFE, mTLS certs), not just human users.
Drives authorization decisions: Identity plus attributes (role, device posture, risk score) feeds the policy engine for least-privilege, context-aware access.
Enables continuous evaluation: A durable identity lets the system re-check trust throughout a session, not just at login.
Q87.What is Broken Authentication and what are common vulnerabilities that lead to it?
Broken Authentication (OWASP: Identification and Authentication Failures) covers weaknesses that let attackers compromise passwords, tokens, or sessions to impersonate legitimate users, undermining the very act of proving who you are.
Credential weaknesses: Allowing weak/default passwords, no protection against credential stuffing or brute force, and no MFA.
Insecure credential storage: Passwords stored in plaintext or with fast/unsalted hashes instead of bcrypt/argon2.
Session management flaws: Predictable or exposed session IDs, tokens in URLs, no rotation after login, sessions that never expire, or missing logout invalidation.
Broken recovery/verification flows: Weak "forgot password" or knowledge-based questions that let attackers reset accounts.
Defenses: Enforce MFA, strong hashing, rate limiting/lockout, secure random session tokens, short expiry with rotation, and prefer vetted identity providers over rolling your own.
Q88.What is Broken Access Control? Why is it considered one of the most critical OWASP vulnerabilities?
OWASP vulnerabilities?Broken Access Control is the failure to properly enforce what an authenticated user is allowed to do, letting them act outside their intended permissions (viewing others' data, escalating privileges, calling admin functions). It ranks #1 on the OWASP Top 10 because it is widespread, easy to exploit, and directly leads to data breaches.
What it is: Authorization (what you can do) fails even when authentication (who you are) succeeds.
Common forms:
Horizontal escalation: accessing another user's records (IDOR/BOLA).
Vertical escalation: a normal user reaching admin functions or endpoints.
Relying on client-side/hidden UI controls or trusting request-supplied roles.
Why it's so critical: Extremely common in real apps, trivial to exploit (just tampering with a request), and the impact is direct unauthorized data access or modification.
Prevention:
Deny by default and enforce checks server-side on every request, never in the UI.
Centralize authorization logic, apply least privilege, and check object ownership.
Add automated tests for cross-user and privilege-escalation attempts, and log access failures.
Q89.Explain horizontal vs. vertical privilege escalation.
Both are privilege escalation (gaining access beyond what you should have), but they differ in direction: horizontal means accessing another user's resources at the same privilege level, while vertical means gaining a higher privilege level than your own.
Horizontal escalation:
Same role, different owner: user A reads or edits user B's data.
Classic cause is IDOR (insecure direct object reference), e.g. changing /orders/123 to /orders/124 and getting someone else's order.
Vertical escalation:
Lower privilege to higher: a normal user reaches admin-only functions.
Causes include missing role checks on endpoints, client-trusted role fields, or tampering with a claim like role: admin.
Prevention (both):
Enforce authorization server-side on every request: check both who you are (role) and what you own (resource ownership).
Never trust client-supplied identity/role; derive it from the verified session or token.
Q90.What are replay attacks in the context of authentication, and how can they be prevented (jti claim, short-lived tokens)?
jti claim, short-lived tokens)?A replay attack is when an attacker captures a valid authentication message (a token, signed request, or credentials) and re-sends it later to impersonate the victim, without needing to forge or decrypt anything. Defenses make each message single-use or short-lived so a captured copy quickly becomes worthless.
Why it works: A validly signed token stays valid until it expires, so a stolen-but-unmodified copy is accepted as-is.
Uniqueness controls:
A jti (JWT ID) claim gives each token a unique id the server can track and reject on reuse (useful for one-time tokens).
Nonces and monotonic counters ensure a given signed request can only be processed once.
Time controls:
Short-lived tokens (small exp) shrink the replay window; pair with refresh tokens for usability.
A timestamp/iat plus a tolerance window lets the server reject stale messages.
Transport and binding:
Always use TLS so tokens can't be sniffed in the first place.
Sender-constrained tokens (mTLS or DPoP) bind a token to a key, so a stolen token can't be replayed by another client.
Q91.What is token theft (e.g., via XSS) and how can it be mitigated, especially when using JWTs?
XSS) and how can it be mitigated, especially when using JWTs?Token theft is an attacker obtaining a valid token (or session) and using it to impersonate the user; the most common vector is XSS, where injected JavaScript reads a token from localStorage or a readable cookie. JWTs are especially risky because they are typically self-contained bearer tokens: whoever holds one is treated as the user, and a stateless JWT can't be easily revoked before it expires.
Storage matters:
Storing tokens in localStorage makes them JS-readable, so any XSS steals them.
Prefer HttpOnly, Secure, SameSite cookies so JS can't read them (add CSRF protection since cookies auto-send).
Prevent the injection: Stop XSS at the source: output encoding, framework escaping, and a strict Content-Security-Policy.
Limit blast radius:
Short-lived access tokens plus rotating refresh tokens minimize how long a stolen token is useful.
Refresh-token rotation with reuse detection can revoke a whole session if a stolen refresh token is replayed.
Sender-constrained tokens (DPoP, mTLS) make a stolen bearer token unusable without the client's key.
Enable revocation: Keep a server-side denylist (by jti) or use opaque reference tokens so compromised tokens can actually be killed.
Q92.What is credential stuffing, and how does it differ from password spraying? How do you defend against each?
Credential stuffing replays username/password pairs leaked from other breaches, betting that users reuse passwords across sites; password spraying instead tries a few common passwords against many accounts to stay under lockout thresholds. In short: stuffing is one guess per account from known real credentials, spraying is few common guesses across many accounts.
Credential stuffing:
Uses breach dumps of valid pairs; high success rate wherever passwords are reused.
Defenses: MFA, block known-breached credentials, bot/device fingerprinting, and IP/velocity anomaly detection.
Password spraying:
Tries a handful of passwords (Password123!, season+year) broadly, deliberately avoiding per-account lockout.
Defenses: ban common passwords, monitor for one IP hitting many accounts, and alert on distributed low-and-slow failures.
Shared mistake:
Per-account rate limits alone miss spraying; you also need per-IP and global failure-rate monitoring.
MFA is the single strongest mitigation for both, since a valid password no longer suffices.
Q93.What defenses against brute-force login attempts do you know — rate limiting, account lockout, CAPTCHA — and their trade-offs?
The main login-abuse defenses are rate limiting, account lockout, and CAPTCHA, and they are complementary rather than interchangeable: each blocks a different attacker behavior and each has a usability or abuse cost, so you layer them and add MFA as the real backstop.
Rate limiting (throttling):
Caps attempts per IP/account/time window; cheap and low-friction.
Trade-off: per-IP limits are evaded by botnets/proxies, and shared NAT can punish innocent users.
Account lockout:
Disables an account after N failures; strongly limits brute-force on a single account.
Trade-off: enables denial-of-service (attacker locks out victims); prefer temporary/exponential backoff over permanent lock.
CAPTCHA:
Forces a human-verification step, killing simple bots; best triggered only after suspicion (risk-based).
Trade-off: hurts UX and accessibility, and can be outsourced/solved by CAPTCHA-farms.
Layering strategy:
Use progressive friction: throttle first, add CAPTCHA on anomalies, back off/lock as a last resort.
None stop credential stuffing on their own; MFA and slow hashing remain essential.
Q94.What is account (username) enumeration, and how do timing and error-message differences leak it?
Account (username) enumeration is when an application lets an attacker determine whether a given username or email exists, letting them build a list of valid targets for spraying, stuffing, or phishing. The leak usually comes from the system responding differently for existing vs. non-existing accounts, whether through messages, HTTP behavior, or timing.
Error-message leaks:
"No such user" vs. "Wrong password" directly confirms existence.
Signup ("email already registered") and password reset ("we sent an email" vs. "not found") leak the same way.
Fix: return one generic message for all cases (e.g. "invalid credentials").
Timing leaks:
A real account runs the expensive password hash; a missing one may short-circuit and respond faster, exposing existence via response time.
Fix: perform equivalent work in both paths (hash against a dummy hash) so timing is uniform.
Other side channels:
Different status codes, redirects, or field-level validation can also distinguish accounts.
Keep responses identical in body, status, and timing across existing/non-existing accounts.
Practical note: Total prevention is hard (users expect "email already in use"), so pair generic responses with rate limiting and monitoring.
Q95.How does a weak signing secret enable a JWT attack, and how do you protect against it?
JWT attack, and how do you protect against it?With HMAC-signed JWTs (HS256), the same secret both signs and verifies tokens, so a weak or guessable secret lets an attacker brute-force it offline and then mint valid tokens with any claims they want (including admin roles or another user's sub). Protection is a long, high-entropy secret and, ideally, asymmetric signing.
Why it works:
A JWT is public; the attacker has the signed material and can try candidate secrets offline with tools until the signature matches.
Once the secret is recovered, they forge tokens the server fully trusts, no login needed.
Protections:
Use a long random secret (256+ bits from a CSPRNG), never a password, word, or short string.
Store it in a secrets manager/env, not in source control, and support rotation.
Prefer asymmetric signing (RS256/ES256): only the private key can sign, so the public verifier being exposed does not enable forgery.
Keep tokens short-lived to limit the blast radius if a secret does leak.
Q96.What are the benefits and challenges of implementing the principle of least privilege in large organizations?
In large organizations, least privilege dramatically reduces risk and improves auditability, but it's operationally hard because entitlements sprawl across thousands of identities and systems, and overly tight access can block legitimate work.
Benefits:
Smaller attack surface and contained breaches.
Cleaner audits and easier compliance (SOX, HIPAA, PCI): you can prove who can access what.
Fewer accidental data leaks and less insider-risk exposure.
Challenges:
Privilege creep: people accumulate access as they change roles and old grants are never revoked.
Defining "minimum" is hard: too tight blocks work and generates support tickets; too loose defeats the purpose.
Scale and visibility: mapping entitlements across many apps, clouds, and service accounts is complex.
Cultural friction: teams resist losing broad access they're used to.
Mitigations that make it workable:
Role-based / attribute-based access to standardize grants instead of one-off permissions.
Just-in-time elevation and time-bound access for privileged tasks.
Periodic access reviews / recertification to reverse privilege creep.
Automated provisioning/deprovisioning tied to HR lifecycle (joiner/mover/leaver).
Q97.Can you explain the confused deputy problem in access control?
The confused deputy problem is when a privileged program (the deputy) is tricked by a less-privileged caller into misusing its authority on the caller's behalf. The deputy has legitimate permissions, but it acts on attacker-supplied input without checking whether the original requester was actually authorized.
The setup:
A service holds broad rights (the deputy) and performs actions for clients.
It uses its own authority for the action but fails to verify the caller's authority for that specific target.
Classic examples:
SSRF: a backend fetches a URL the user supplies and reaches internal services the user could never reach directly.
CSRF: the browser (deputy) attaches the victim's cookies to a forged cross-site request.
A cloud service assuming a powerful role to act on tenant data without checking which tenant asked.
Root cause: Authority is derived from the deputy's identity (ambient authority) instead of the requester's.
Defenses:
Propagate and check the original caller's identity/permissions on every downstream action.
Use capability-style tokens (the request carries proof of authorization for the specific resource), e.g. scoped tokens or the external ID pattern for cross-account role assumption.
Anti-CSRF tokens and strict allow-lists for server-side fetches.
Q98.What does 'fail-secure' or 'fail-closed' mean for an access-control decision, and why is it preferred over failing open?
Q99.Explain Attribute-Based Access Control (ABAC) and the roles of PDP, PEP, and PIP.
ABAC) and the roles of PDP, PEP, and PIP.Q100.What is Relationship-Based Access Control (ReBAC), such as the Google Zanzibar model, and when is it useful?
ReBAC), such as the Google Zanzibar model, and when is it useful?Q101.What is externalized authorization with a policy engine (e.g., OPA/Rego), and what are its benefits?
OPA/Rego), and what are its benefits?Q102.How do you enforce object-level or row-level authorization and tenant isolation in a multi-tenant system?
Q103.Why is a timing-safe comparison important when verifying secrets or tokens?
Q104.What are the challenges of JWT revocation, and what strategies are used to mitigate them?
JWT revocation, and what strategies are used to mitigate them?Q105.What is the difference between symmetric and asymmetric signing algorithms in JWT?
JWT?Q106.What are the security implications of using JWT?
JWT?Q107.What is the difference between opaque tokens and self-contained (e.g., JWT) tokens, and when would you choose each?
JWT) tokens, and when would you choose each?Q108.What is token binding, and how does it help prevent token theft and replay?
Q109.What is the difference between JWS and JWE, and when would you need an encrypted JWT?
JWS and JWE, and when would you need an encrypted JWT?Q110.How does a JWKS endpoint and public-key rotation work for validating signed tokens?
JWKS endpoint and public-key rotation work for validating signed tokens?Q111.Describe the Authorization Code flow with PKCE in OAuth 2.0. Why is PKCE important, especially for public clients?
PKCE in OAuth 2.0. Why is PKCE important, especially for public clients?Q112.Explain other OAuth 2.0 grant types such as Client Credentials, Device Code, Implicit, and Resource Owner Password Credentials, and discuss their use cases and why some are deprecated or discouraged.
OAuth 2.0 grant types such as Client Credentials, Device Code, Implicit, and Resource Owner Password Credentials, and discuss their use cases and why some are deprecated or discouraged.Q113.What is the difference between the front channel and back channel in OAuth flows, and why does it matter for security?
OAuth flows, and why does it matter for security?Q114.What are the key changes introduced in OAuth 2.1 compared to OAuth 2.0?
OAuth 2.1 compared to OAuth 2.0?Q115.What is OAuth token exchange, and when would you use it?
OAuth token exchange, and when would you use it?Q116.Explain the difference between delegation and impersonation, and how the on-behalf-of flow works.
on-behalf-of flow works.Q117.Compare SAML and OpenID Connect. Discuss their differences in data format, use cases, and when you would choose one over the other.
SAML and OpenID Connect. Discuss their differences in data format, use cases, and when you would choose one over the other.Q118.What is the difference between SP-initiated and IdP-initiated SSO?
SP-initiated and IdP-initiated SSO?Q119.What is federated identity, and how is trust established between organizations?
Q120.What is step-up (adaptive) authentication, and when would you require it?
Q121.What does 'phishing-resistant authentication' mean, and why is WebAuthn considered phishing-resistant?
WebAuthn considered phishing-resistant?Q122.Discuss common patterns for service-to-service authentication in a microservices architecture, such as mTLS and signed service tokens.
mTLS and signed service tokens.Q123.How do you implement authorization checks with JWT claims, especially in a microservices architecture?
JWT claims, especially in a microservices architecture?Q124.How does certificate-based (mutual TLS) authentication work as an identity mechanism?
Q125.Should authorization be enforced at the API gateway or inside each service? Discuss the trade-offs.
Q126.How is a token propagated across services in a microservices call chain, and what are the risks?
Q127.Explain the role of micro-segmentation in a Zero Trust model.
Q128.What is broken object-level authorization (BOLA) or Insecure Direct Object References (IDOR), and how do you prevent them?
BOLA) or Insecure Direct Object References (IDOR), and how do you prevent them?Q129.How do you design a secure password-reset and account-recovery flow?
Q130.What is an open-redirect vulnerability via the redirect_uri in OAuth, and how do you prevent it?
redirect_uri in OAuth, and how do you prevent it?Q131.Explain JWT-specific attacks such as 'alg:none' bypass and algorithm confusion (RS256 to HS256 downgrade). How are they mitigated?
JWT-specific attacks such as 'alg:none' bypass and algorithm confusion (RS256 to HS256 downgrade). How are they mitigated?