Authentication & Authorization

Proving identity and controlling access — sessions and cookies, JWTs and their trade-offs, OAuth 2.0 and OpenID Connect flows (authorization code + PKCE), SSO, MFA and passkeys, API keys, and authorization models (RBAC, ABAC, ReBAC).

Intermediate 6 min readLesson 11 of 14 Interview Q&A

Two different questions:

  • Authentication (authn): who are you? — verifying identity (password, passkey, SSO).
  • Authorization (authz): what may you do? — checking permissions for each action.

HTTP is stateless, so after login the server needs a way to recognise subsequent requests: sessions or tokens.

Password login done right

  • Store passwords with a slow, salted hash — Argon2id, bcrypt or scrypt — never plain text or fast hashes like SHA-256 (Password storage).
  • Rate-limit login attempts and add lockouts or CAPTCHA after failures; check passwords against breach lists.
  • Return the same error for "unknown user" and "wrong password" to avoid account enumeration.
  • Offer multi-factor authentication.

Session-based authentication

BrowserServerSession storePOST /login (email, password)create session sid → userIdSet-Cookie: sid=…; HttpOnly; Secure; SameSite=LaxGET /account (Cookie: sid=…)look up sid200 account page

The cookie holds only a random, unguessable session ID; the data lives on the server (Redis, a database).

Cookie attributePurpose
HttpOnlyJavaScript can't read it — limits XSS token theft
SecureSent only over HTTPS
SameSite=Lax / StrictNot sent on most cross-site requests — CSRF defence (Web security)
Max-Age / ExpiresLifetime
Path, DomainScope; prefix __Host- to lock it to one origin

Pros: easy revocation (delete the session), small cookie, server controls everything. Cons: needs a shared session store when scaling horizontally. Regenerate the session ID on login (prevents session fixation).

Token-based authentication and JWT

A JSON Web Token is a signed, self-contained token: header.payload.signature, each Base64URL-encoded.

eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiI3Iiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzY0ODAwMDAwfQ.MEUCIQ…

Header:  { "alg": "ES256", "typ": "JWT" }
Payload: { "sub": "7", "role": "admin", "iss": "auth.acme.com", "aud": "api.acme.com", "exp": 1764800000 }
Signature: sign(header + "." + payload, private key)

The server verifies the signature and reads claims without a database lookup — useful for stateless APIs and microservices, where any service with the public key can verify (Digital signatures).

Access and refresh tokens

  • Access token: short-lived, sent with every API call (Authorization: Bearer …).
  • Refresh token: long-lived, stored securely, used only to get new access tokens. Rotate it on each use and detect reuse (a sign of theft).

Sessions vs JWTs

Server sessionsJWTs
StateOn the serverIn the token
RevocationImmediateHard; short expiry + refresh
ScalingShared store (Redis)Stateless verification
Best forTraditional web appsAPIs, mobile, service-to-service, federated identity

For a single web app, cookie sessions are usually simpler and safer. JWTs shine when tokens must cross trust boundaries.

OAuth 2.0 and OpenID Connect

OAuth 2.0 is a framework for delegated authorization: letting an app access a user's resources at another service without seeing their password ("Allow PhotoPrinter to read your Google Photos"). OpenID Connect (OIDC) adds an identity layer on top — an ID token (a JWT) saying who the user is — and powers "Sign in with Google/Microsoft/GitHub" and enterprise SSO.

RoleExample
Resource ownerThe user
ClientThe app wanting access
Authorization serverGoogle's or Okta's login and consent service
Resource serverThe API holding the data

Authorization code flow with PKCE

The recommended flow for web, mobile and single-page apps:

User/BrowserApp (client)Auth serverAPIredirect to /authorize + code_challengelogin + consentredirect back with ?code=…codePOST /token (code + code_verifier)access token (+ ID token, refresh)API call with Bearer token
  • PKCE (Proof Key for Code Exchange): the client sends a hash of a random secret (code_challenge) at the start and the secret itself (code_verifier) when redeeming the code, so an intercepted code is useless.
  • The state parameter (and OIDC's nonce) prevent CSRF and replay.
  • Older flows — implicit and password grant — are deprecated. Machine-to-machine uses the client credentials flow; TVs and CLIs use the device code flow.

Scopes limit what a token can do (read:photos). OAuth is not authentication by itself — use OIDC's ID token for identity.

SSO

Single sign-on lets users log in once with a central identity provider (Okta, Entra ID, Google Workspace, Keycloak) and access many apps, via OIDC or the older XML-based SAML. Companies get central offboarding and policy; SCIM syncs user provisioning.

Multi-factor authentication and passkeys

MFA combines factors: something you know (password), have (phone, security key), are (biometric).

MethodStrength
SMS codesWeak — SIM swapping, phishing
TOTP apps (6-digit codes)Good, but phishable
Push approvalGood; vulnerable to "MFA fatigue" spam
Passkeys / WebAuthn / FIDO2 security keysStrongest — phishing-resistant

Passkeys replace passwords with public-key cryptography: the device holds a private key per site, unlocked with biometrics or a PIN; the server stores only the public key. The browser binds each credential to the site's origin, so a phishing site can't use it, and there's no shared secret to leak in a breach.

API keys

Simple secret strings for server-to-server access or developer APIs. Store only a hash of the key, show it once, allow rotation and scoping, prefix it for leak detection (sk_live_…), and never ship keys in front-end code.

Authorization models

ModelIdeaExample
RBAC — role-basedUsers get roles; roles have permissionsadmin, editor, viewer
ABAC — attribute-basedPolicies over user, resource and context attributes"Managers can approve expenses under ₹1L in their own department during business hours"
ReBAC — relationship-basedPermissions follow relationships in a graphGoogle Docs: owner/editor/viewer of a doc or its folder (Zanzibar; OpenFGA, SpiceDB)
ACLsPer-resource lists of who can do whatFile permissions

Rules that prevent most authz bugs:

  • Deny by default; check permissions on the server for every request, never just hide buttons in the UI.
  • Check object-level access: GET /invoices/123 must verify that invoice 123 belongs to the caller. Missing checks (IDOR / broken object-level authorization) are the top API vulnerability.
  • Centralise policy (middleware, a policy engine like OPA or Cedar) rather than scattering if checks.
  • Principle of least privilege.
Key takeaways
  • Authentication proves identity; authorization decides permissions — check both server-side on every request.
  • Sessions: random ID in an HttpOnly, Secure, SameSite cookie; state on the server; easy revocation.
  • JWTs: signed, readable claims for stateless verification; short-lived access tokens, rotating refresh tokens, strict validation.
  • OAuth 2.0 delegates access; OIDC adds identity; use authorization code + PKCE.
  • Passkeys (WebAuthn) are phishing-resistant and remove shared secrets.
  • RBAC, ABAC and ReBAC model permissions; always enforce object-level checks (avoid IDOR).
Interview questions
QShould a web app use sessions or JWTs?medium

For a typical server-rendered or single-domain web app, cookie-based sessions are simpler and safer: the server can revoke them instantly and the cookie is HttpOnly. JWTs suit stateless APIs, mobile clients, microservices and federation, where tokens are verified by services that don't share a session store. If you use JWTs, keep access tokens short-lived, use rotating refresh tokens, validate algorithm, expiry, issuer and audience, and avoid storing them in localStorage.

QExplain the OAuth authorization code flow with PKCE.hard

The client creates a random code_verifier and sends its SHA-256 hash (code_challenge) when redirecting the user to the authorization server. The user logs in and consents; the server redirects back with a short-lived authorization code. The client exchanges the code plus the original code_verifier at the token endpoint; the server checks that the verifier hashes to the challenge before issuing tokens. An attacker who intercepts the code can't redeem it without the verifier. The state parameter protects the redirect against CSRF.