Every real system has to answer two questions for every request: "Who are you?" and "Are you allowed to do this?" A banking app must not show your balance to a stranger, and a normal user must not be able to delete other people's posts. In the chapter API Gateway & Service Discovery we saw that the gateway is a natural place to check credentials. In this chapter we learn what those credentials actually are: sessions, tokens, OAuth 2.0, OpenID Connect and JWT, and how large systems combine them.
Authentication (AuthN) is verifying who a user or service is. Authorization (AuthZ) is deciding what that verified identity is allowed to do.
A simple way to remember: authentication is showing your ID card at the college gate; authorization is the rule that only final-year students may enter the placement cell. Authentication always comes first, because you cannot decide permissions for someone you have not identified.
Authentication vs Authorization
Aspect | Authentication | Authorization |
|---|---|---|
Question | Who are you? | What may you do? |
Input | Password, OTP, passkey, certificate, token | Identity + roles, scopes, attributes, policies |
Output | A verified identity (user ID) | Allow or deny |
Failure HTTP status | 401 Unauthorized (missing or invalid credentials) | 403 Forbidden (identity known, access refused) |
Examples | Login with password + OTP, "Sign in with Google" | Admin-only routes, "can edit own posts only" |
Yes, the name of status 401 is confusing: it says "Unauthorized" but it really means "unauthenticated". The HTTP specification (RFC 9110) defines 401 as "lacks valid authentication credentials" and 403 as "understood the request but refuses to fulfill it".
Step 1: Verifying the User
Passwords, Done Correctly
Most logins still start with a password. The server must never store the password itself, not even encrypted. It stores a slow, salted hash:
Salt: a random value stored per user and mixed into the hash, so two users with the same password get different hashes and precomputed "rainbow tables" are useless.
Slow hash: a password-hashing function such as Argon2id (OWASP's first choice), scrypt or bcrypt. They are deliberately slow and memory-hungry so an attacker who steals the database can try only a few guesses per second per CPU, instead of billions with a fast hash like SHA-256.
Multi-Factor Authentication
A factor is something you know (password), something you have (phone, security key) or something you are (fingerprint). Combining two different kinds is MFA. Common second factors: TOTP codes from an authenticator app, SMS OTP (weaker, because SIM swaps exist), and passkeys (WebAuthn/FIDO2), which use public-key cryptography and resist phishing because the key only works on the real website's domain.
Step 2: Remembering the User
HTTP is stateless (chapter Client-Server Architecture & APIs). After a successful login the server must give the client something to send on every later request, so the user does not type the password each time. There are two main families.
Server-Side Sessions (Stateful)
1. POST /login (username, password)
2. Server verifies, creates a session: sessions["s9f3..."] = {user: 42, expires: ...}
3. Response: Set-Cookie: sid=s9f3...; HttpOnly; Secure; SameSite=Lax
4. Every later request carries the cookie: Cookie: sid=s9f3...
5. Server looks up "s9f3..." in the session store -> user 42
The session ID is just a long random string with no meaning; the real data lives on the server. With many app servers, the session store must be shared (usually Redis), otherwise a user logged in on server A looks logged out on server B. This is the "sticky session vs shared store" issue from Load Balancing.
Cookie flags matter: HttpOnly stops JavaScript from reading the cookie (protection against XSS theft), Secure sends it only over HTTPS, and SameSite limits sending it on cross-site requests (protection against CSRF).
Tokens (Self-Contained, Often Stateless)
Instead of a meaningless ID, the server hands out a signed token that itself contains the user ID, expiry and permissions. Any service holding the verification key can check it without a database lookup. The most common format is the JWT, covered below.
Aspect | Server-side session | Self-contained token (JWT) |
|---|---|---|
Where state lives | Server (session store) | Inside the token |
Lookup per request | Yes (fast with Redis, but a dependency) | No, only a signature check |
Logout / revoke | Easy: delete the session | Hard: token is valid until it expires |
Size | Tiny (about 32 bytes) | Larger (hundreds of bytes) |
Best fit | Classic web apps, one backend | APIs, microservices, mobile apps, third-party access |
JSON Web Token (JWT)
A JWT (RFC 7519) is a compact, URL-safe string that carries a set of claims (statements such as "subject is user_42" or "expires at time T"), protected by a digital signature or MAC so that any change is detected.
Structure
A signed JWT has three Base64URL-encoded parts separated by dots:
eyJhbGciOi... . eyJpc3MiOi... . Co5iaXW1wo...
\___________/ \___________/ \___________/
HEADER PAYLOAD SIGNATURE
{"alg":"HS256", {"sub":"user_42", HMAC-SHA256(
"typ":"JWT"} "exp":1800000900, header + "." + payload,
"scope":"..."} secret)
The important point beginners miss: Base64URL is encoding, not encryption. Anyone can decode the header and payload and read them. The signature only guarantees integrity and origin (nobody changed it, and it came from the key holder). Never put passwords, Aadhaar numbers or other secrets in a normal JWT. If the contents must be hidden, use an encrypted JWT (JWE, RFC 7516), or simply keep the data on the server.
Registered Claims
Claim | Meaning | Why it matters |
|---|---|---|
| Issuer: who created the token | Reject tokens from unknown issuers |
| Subject: whom the token is about (user ID) | The identity used for authorization |
| Audience: who the token is meant for | A token for the orders API must not work on the payments API |
| Expiration time (seconds since 1970) | Limits damage if stolen |
| Not before | Token is not valid before this time |
| Issued at | Age of the token |
| JWT ID: unique identifier | Lets you denylist one token or detect replay |
Applications add their own claims too, such as scope or roles.
Signing Algorithms
HS256 (HMAC with SHA-256): one shared secret both signs and verifies. Simple and fast, but every verifier can also create tokens. Fine inside one service; risky when many services verify.
RS256 (RSA) / ES256 (ECDSA) / EdDSA: the auth server signs with a private key; services verify with the public key, which it publishes at a JWKS (JSON Web Key Set) URL. A compromised API server cannot forge tokens. This is the usual choice in microservices.
Worked Example: Build and Verify a JWT by Hand
This Python program uses only the standard library, so you can see that a JWT is nothing magical. In real projects, use a well-tested library (for example PyJWT, jjwt or jose) instead of writing your own.
import base64, hashlib, hmac, json
def b64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def b64url_decode(text: str) -> bytes:
padding = "=" * (-len(text) % 4)
return base64.urlsafe_b64decode(text + padding)
def sign_jwt(payload: dict, secret: bytes) -> str:
header = {"alg": "HS256", "typ": "JWT"}
h = b64url_encode(json.dumps(header, separators=(",", ":")).encode())
p = b64url_encode(json.dumps(payload, separators=(",", ":")).encode())
signing_input = f"{h}.{p}".encode("ascii")
sig = hmac.new(secret, signing_input, hashlib.sha256).digest()
return f"{h}.{p}.{b64url_encode(sig)}"
def verify_jwt(token: str, secret: bytes, now: int, audience: str) -> dict:
try:
h, p, s = token.split(".")
except ValueError:
raise ValueError("malformed token")
header = json.loads(b64url_decode(h))
if header.get("alg") != "HS256": # never trust the alg blindly
raise ValueError("unexpected algorithm")
expected = hmac.new(secret, f"{h}.{p}".encode("ascii"), hashlib.sha256).digest()
if not hmac.compare_digest(expected, b64url_decode(s)):
raise ValueError("bad signature")
claims = json.loads(b64url_decode(p))
if claims["exp"] <= now:
raise ValueError("token expired")
if claims["aud"] != audience:
raise ValueError("wrong audience")
return claims
SECRET = b"a-32-byte-or-longer-random-secret!!"
NOW = 1_800_000_000 # fixed "current time" so output is repeatable
token = sign_jwt({"iss": "https://auth.example.com", "sub": "user_42",
"aud": "orders-api", "iat": NOW, "exp": NOW + 900,
"scope": "orders:read"}, SECRET)
print("Token:", token)
print("Parts:", len(token.split(".")))
print("Header :", b64url_decode(token.split(".")[0]).decode())
print("Payload:", b64url_decode(token.split(".")[1]).decode())
print("Valid ->", verify_jwt(token, SECRET, NOW + 60, "orders-api")["sub"])
# Attack 1: change the payload (privilege escalation) but keep the old signature
h, p, s = token.split(".")
evil = json.loads(b64url_decode(p)); evil["scope"] = "orders:admin"
forged = f"{h}.{b64url_encode(json.dumps(evil, separators=(',', ':')).encode())}.{s}"
for label, tok, t, aud in [("Tampered", forged, NOW + 60, "orders-api"),
("Expired ", token, NOW + 901, "orders-api"),
("Wrong aud", token, NOW + 60, "payments-api")]:
try:
verify_jwt(tok, SECRET, t, aud)
except ValueError as e:
print(f"{label} -> rejected: {e}")
Output:
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyXzQyIiwiYXVkIjoib3JkZXJzLWFwaSIsImlhdCI6MTgwMDAwMDAwMCwiZXhwIjoxODAwMDAwOTAwLCJzY29wZSI6Im9yZGVyczpyZWFkIn0.Co5iaXW1woGLmVklQhvYrbvkLAnHKcUaavvyHG3WNKk
Parts: 3
Header : {"alg":"HS256","typ":"JWT"}
Payload: {"iss":"https://auth.example.com","sub":"user_42","aud":"orders-api","iat":1800000000,"exp":1800000900,"scope":"orders:read"}
Valid -> user_42
Tampered -> rejected: bad signature
Expired -> rejected: token expired
Wrong aud -> rejected: wrong audience
Notice three things. Anyone could decode the payload (we printed it without the secret). Changing even one character of the payload breaks the signature. And hmac.compare_digest compares in constant time, so an attacker cannot guess the signature byte by byte from response timing.
Famous JWT Pitfalls
alg: none: the spec allows unsigned JWTs. Old libraries that trusted the header'salgaccepted forged tokens with no signature. Always fix the allowed algorithms on the server.Algorithm confusion: an attacker changes RS256 to HS256 and signs with the server's public key as the HMAC secret. A naive library then verifies it. Again: the server, not the token, decides the algorithm.
Not checking
aud,issandexp. A valid signature is not enough. RFC 8725 (JWT Best Current Practices) lists these checks.Weak HMAC secrets: a short secret can be brute-forced offline from any captured token. Use at least 256 random bits for HS256.
The Revocation Problem
If a user logs out or is banned, a stateless JWT stays valid until exp. Systems handle this with a combination of:
Short-lived access tokens (typically 5 to 15 minutes), so a stolen token expires soon.
Refresh tokens: a long-lived credential, stored carefully and checked against the database, used only to get new access tokens. Revoking the refresh token ends the session within one access-token lifetime.
Refresh token rotation: every refresh returns a new refresh token and invalidates the old one. If an old one is ever reused, the server knows it was stolen and kills the whole token family.
A denylist of
jtivalues in Redis for emergency revocation, accepting a small lookup cost.
OAuth 2.0: Delegated Authorization
Suppose a resume-builder app wants to read your profile from LinkedIn, or a photo-printing site wants your Google Photos. You should never give them your password. OAuth 2.0 (RFC 6749) solves this.
OAuth 2.0 is an authorization framework that lets a user grant a third-party application limited access (scopes) to their resources on another service, by issuing the app an access token instead of sharing the user's password.
The Four Roles
Role | Who it is | Example |
|---|---|---|
Resource owner | The user who owns the data | You |
Client | The app that wants access | Resume-builder app |
Authorization server | Authenticates the user, asks for consent, issues tokens | accounts.google.com |
Resource server | The API holding the data; accepts access tokens | Google Photos API |
Clients are either confidential (a backend that can keep a client secret) or public (mobile apps and single-page apps, which cannot hide a secret because the code runs on the user's device).
Authorization Code Flow with PKCE
This is the recommended flow for almost every user-facing app today. PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixy") protects against an attacker who steals the authorization code.
User/Browser Client app Authorization server Resource server
| | | |
| click "Connect" | | |
|------------------->| create random code_verifier | |
| | challenge = BASE64URL(SHA256(verifier)) |
|<-- redirect to /authorize?response_type=code&client_id=..&scope=photos.read |
| &redirect_uri=..&state=xyz&code_challenge=..&code_challenge_method=S256
|------------------------------------------------>| |
| login + consent screen ("Allow read access to photos?") |
|<-- redirect to redirect_uri?code=AUTH_CODE&state=xyz |
|------------------->| | |
| | POST /token (code, code_verifier, client auth) |
| |----------------------------->| checks SHA256(verifier) |
| |<-----------------------------| == stored challenge |
| | access_token (+ refresh_token, + id_token if OIDC) |
| | GET /photos Authorization: Bearer access_token |
| |------------------------------------------------------->|
| |<-------------------------------------- photos ---------|
Why two steps (code, then token)? The browser redirect travels through places that can leak: browser history, logs, malicious apps registered for the same URL scheme. So only a short-lived, one-time code goes through the browser. The real tokens are fetched over a direct back-channel HTTPS call.
Why PKCE? If an attacker steals the code, they still cannot exchange it, because they do not know the random code_verifier that only the real client holds. The state parameter separately protects against CSRF on the redirect.
The S256 method can be checked with the official test vector from RFC 7636:
import base64, hashlib, secrets
def code_challenge(verifier: str) -> str:
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
# 1. Fresh random verifier, as a real client would create
fresh = secrets.token_urlsafe(32) # 43 characters, high entropy
print("fresh verifier length:", len(fresh))
# 2. The test vector from RFC 7636, Appendix B
verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
print("code_verifier :", verifier)
print("code_challenge:", code_challenge(verifier))
Output:
fresh verifier length: 43
code_verifier : dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
code_challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
Other Grant Types
Grant | Use case | Status today |
|---|---|---|
Authorization code + PKCE | Web apps, SPAs, mobile apps acting for a user | Recommended. PKCE is required for public clients and recommended for all. |
Client credentials | Service-to-service, no user involved (a cron job calling an API) | Recommended for machine-to-machine |
Device authorization (RFC 8628) | Smart TVs, CLIs: "go to example.com/device and enter code ABCD-1234" | Recommended for input-limited devices |
Refresh token | Get a new access token without asking the user again | Used with the above; public clients must rotate or sender-constrain it |
Implicit | Old SPAs; token returned directly in the URL fragment | Should not be used (token leakage) |
Resource owner password credentials | App collects the user's password and sends it | Must not be used |
These rules come from the OAuth 2.0 Security Best Current Practice, RFC 9700 (January 2025). It also requires the authorization server to match redirect URIs exactly, not by prefix. OAuth 2.1 is an IETF draft that folds these practices into one document (PKCE everywhere, no implicit or password grant); as of late 2026 it is still an Internet-Draft, not a published RFC, but its rules already describe how modern providers behave.
Scopes
A scope is a named permission the client asks for, such as photos.read or repo:status. The user sees them on the consent screen, and the access token carries the granted scopes. Ask for the least you need: an app that only reads your calendar should not get permission to delete your email.
OpenID Connect: Authentication on Top of OAuth
OAuth 2.0 was designed for authorization: an access token says "the bearer may read photos", not "this is user Priya". Using a plain access token as proof of login is a known mistake. OpenID Connect (OIDC) adds an identity layer:
The client includes the scope
openid(plusprofile,emailas needed).The token response includes an ID token: a JWT whose
audis the client, whosesubis a stable user ID, plus anoncethe client sent to prevent replay.There is a standard UserInfo endpoint and a discovery document at
/.well-known/openid-configurationlisting endpoints and the JWKS URL.
"Sign in with Google/Microsoft/Apple" buttons are OIDC. Enterprises also use SAML 2.0, an older XML-based standard, for single sign-on (SSO) into tools like HR and payroll systems.
Access token (OAuth) | ID token (OIDC) | |
|---|---|---|
Purpose | Call an API | Tell the client who logged in |
Audience | The resource server (API) | The client app |
Format | Opaque string or JWT (RFC 9068 profile) | Always a JWT |
Send it to APIs? | Yes | No |
Authorization Models
Once you know who the caller is, you need rules for what they may do.
RBAC (Role-Based Access Control): permissions attach to roles (student, teacher, admin), and users get roles. Simple and auditable; most apps start here.
ABAC (Attribute-Based): rules use attributes of the user, resource and environment: "a teacher may edit marks of courses they teach, only before the result date". Flexible but harder to reason about.
ReBAC (Relationship-Based): permission comes from relationships in a graph: "you can view this document because you are in a group that is an editor of the parent folder". Google described its global system for this, Zanzibar, in a 2019 paper; open-source systems such as OpenFGA and SpiceDB follow the same idea.
ACL (Access Control List): each resource keeps a list of who may do what, like file permissions.
A common mistake is checking only the role and not ownership. "User is logged in and has role customer" does not mean they may view /orders/1234; you must also check that order 1234 belongs to them. Missing this check (often called IDOR, broken object-level authorization) is the number one item in the OWASP API Security Top 10.
Putting It Together: Auth in a Microservices System
(1) login via OIDC
Browser/App <--------------------------> Auth server (IdP)
| | publishes public keys
| (2) Bearer access token (JWT, 10 min) | at /.well-known/jwks.json
v v
+-------------+ (3) verify signature, exp, aud, iss (cached JWKS)
| API Gateway | reject with 401 if invalid; rate limit per user
+-------------+
| (4) forwards request + verified user ID / scopes
v
+-----------+ (5) mTLS / service token +-----------+
| Orders |--------------------------->| Payments |
| service | | service |
+-----------+ +-----------+
(6) business authorization: "does order 1234 belong to user_42?"
Coarse checks at the edge (valid token, required scope) happen in the gateway, so bad requests never reach the services.
Fine-grained checks (ownership, business rules) stay inside each service, because only it knows the data.
Service-to-service calls use mutual TLS or client-credentials tokens, so an attacker inside the network cannot simply call internal APIs (the "zero trust" idea).
Public keys are fetched from JWKS and cached, so verification needs no network call per request. Key rotation works by publishing the new key alongside the old one (identified by the
kidheader) before switching.
Where Should a Browser Keep Tokens?
Tokens in localStorage can be stolen by any XSS bug. The current recommendation for browser apps is the Backend-for-Frontend (BFF) pattern: a small server-side component does the OAuth flow, keeps the tokens, and gives the browser only an HttpOnly, Secure, SameSite session cookie. Mobile apps store tokens in the OS keychain/keystore.
Common Mistakes
Thinking JWTs are encrypted. A signed JWT is readable by anyone; it is only tamper-proof.
Using OAuth access tokens as proof of login. Use OIDC ID tokens (and validate
audandnonce).Long-lived access tokens (days or months) with no revocation path.
Letting the token choose the algorithm (
alg: none, RS256 to HS256 confusion).Storing passwords with MD5/SHA-1/SHA-256, or unsalted. Use Argon2id, scrypt or bcrypt.
Returning 403 when no credentials were sent (it should be 401), or leaking whether a username exists through different error messages.
Checking roles but not ownership of the specific object.
Interview Questions
1. What is the difference between authentication and authorization? Which HTTP codes go with each?
Authentication verifies identity; authorization decides permissions for that identity. Missing or invalid credentials return 401 Unauthorized; a known identity without permission gets 403 Forbidden.
2. Sessions or JWTs: which would you choose for a microservices system, and what is the trade-off?
Short-lived JWT access tokens signed with an asymmetric key, because any service can verify them locally using the public key with no shared session store. The cost is revocation: a JWT stays valid until it expires, so keep access tokens short (minutes) and use revocable, rotating refresh tokens, plus a jti denylist for emergencies. For a single classic web app, server-side sessions are simpler and revoke instantly.
3. Can a user read the contents of a JWT? Can they modify it?
They can read it, because header and payload are only Base64URL-encoded. They cannot modify it undetected: any change invalidates the signature, which they cannot recompute without the key.
4. Why does the authorization code flow return a code first instead of the token directly?
The front-channel redirect through the browser can leak through history, logs or malicious apps. Sending only a short-lived, one-time code there, and exchanging it for tokens over a direct back-channel request (with client authentication and/or PKCE), keeps tokens out of the browser URL.
5. What attack does PKCE prevent and how?
Authorization code interception. The client sends a hash of a random secret (code_challenge) with the authorization request and the secret itself (code_verifier) when redeeming the code. An attacker who steals the code does not know the verifier, so the token endpoint refuses the exchange.
6. Is OAuth 2.0 an authentication protocol?
No. It is a delegated authorization framework. OpenID Connect builds authentication on top of it by adding the ID token, the openid scope, UserInfo and discovery.
7. Why prefer RS256/ES256 over HS256 when many services verify tokens?
With HS256 every verifier holds the same secret and could therefore mint tokens; one compromised service compromises all. With asymmetric algorithms only the auth server has the private key; services hold only the public key, which can verify but not sign.
Summary
Authentication = who you are (401 on failure); authorization = what you may do (403 on failure).
Store passwords with a salted slow hash (Argon2id, scrypt, bcrypt); add MFA, ideally passkeys.
Sessions keep state on the server and revoke easily; JWTs are self-contained, verified locally, but hard to revoke.
A JWT is
header.payload.signature, Base64URL-encoded, signed not encrypted. Always validate signature with a fixed algorithm, plusexp,iss,aud.Use short-lived access tokens with rotating refresh tokens.
OAuth 2.0 delegates limited access via scopes. Use authorization code + PKCE for users, client credentials for machines; implicit and password grants are deprecated (RFC 9700).
OIDC adds login (ID token) on top of OAuth.
Check tokens at the gateway, check ownership and business rules inside services, and secure service-to-service calls.
Authenticate once, authorize every time: a valid token tells you who is asking, not whether they may touch this particular resource.