SE·109
Identity and Access
Who is calling and what they may do: identity, authentication factors and passkeys, sessions and cookies, OAuth 2 and its flows (authorisation code with PKCE, client credentials, device, token exchange), OpenID Connect, JWTs and how to validate them, access and refresh tokens, scopes, sender-constrained tokens (DPoP, mTLS), authorisation models (RBAC, ABAC, ReBAC), policy engines (OPA, Cedar, OpenFGA), broken object-level authorisation, and workload identity with short-lived credentials, in Java/Spring, Go, Python, Rust and TypeScript.
Start here: who is calling, and what may they do?
Every request to a system raises two separate questions. Authentication: who is this? Authorisation: is this caller allowed to do this action on this object? Most identity bugs come from answering the first and forgetting the second, or from trusting a token without checking it properly.
Tokens: a signed statement, checked on every request
After you sign in, an identity provider usually hands the app an access token: a small signed document saying who you are, which API it is for and what you may do. A JWT has three base64 parts (header, payload, signature):
token length: 288 chars; header: {'alg': 'EdDSA', 'typ': 'JWT'}
payload (readable by anyone): sub=user-42 scope=orders:read
Base64 is not encryption: never put secrets in a JWT payload. What makes the token trustworthy is the signature, and the checks the API runs:
valid token ACCEPT sub=user-42 scope=orders:read
expired 10 min ago REJECT ExpiredSignatureError
audience billing-api REJECT InvalidAudienceError
issuer evil.test REJECT InvalidIssuerError
payload edited, old signature REJECT InvalidSignatureError
signed by a different key REJECT InvalidSignatureError
alg=none (unsigned) REJECT InvalidAlgorithmError
Each rejection is one line of the validation you must not skip: the signature against the issuer's key, a fixed list of allowed algorithms (so an unsigned alg=none token is refused), expiry, the issuer, and the audience (a token minted for the billing API must not open the orders API).
Logging in safely: OAuth with PKCE
Apps don't collect your password; they send you to the identity provider, which returns a one-time authorisation code the app exchanges for tokens. PKCE ties that code to the app that started the login:
code_verifier (kept by the app): B1EuRpC2t2ELazgviECY… 64 chars
code_challenge (sent first) : 8tNUSC70rvC8mHXZlWsOMVLOWfwwMmLKq6uS9uXo7IY
server check at token exchange : True
a stolen code with a guessed verifier: False
The app sends only the SHA-256 challenge at the start and reveals the verifier when exchanging the code. Someone who intercepts the code can't redeem it without the verifier, and the hash can't be reversed to get it.
Authorisation on every object
Authentication says the caller is user-42. That doesn't mean they may read order 102:
owner check OFF: user-42 → order 101: 200, order 102: 200
owner check ON : user-42 → order 101: 200, order 102: 404
Without the per-object check, any signed-in user can read anyone's order by changing an ID in the URL. This is broken object-level authorisation (BOLA), the top API risk in the OWASP API Top 10. Returning 404 rather than 403 also avoids confirming that the object exists.
Roles versus relationships
RBAC: asha may update-status of ANY order: True
ReBAC: asha may update order:101 (her kitchen): True
ReBAC: after order moves to blr-1: False
ReBAC: ravi owns order:101: True
Role-based access (RBAC) says "kitchen staff may update orders", which here means every order in every city. Relationship-based access (ReBAC, the model behind Google's Zanzibar and OpenFGA) stores facts like "order 101 belongs to kitchen hyd-1" and "asha is a member of hyd-1", and derives permission from them; when the order moves, her access follows automatically. Attribute-based access (ABAC) adds conditions such as time, region or device.
How deep to go in identity and access
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Distinguish authentication from authorisation; explain sessions, tokens, MFA and passkeys |
| L2 | Integrate an OIDC login with PKCE and validate tokens correctly with a library |
| L3 | Explain OAuth flows, JWT validation rules, token lifetimes and RBAC/ABAC/ReBAC trade-offs |
| L4 | Find token-validation, BOLA and privilege-escalation flaws in code and tests |
| L5 | Design an organisation's identity architecture: IdP, workload identity, policy engine, token strategy |
| L6 | Set identity and access standards and govern them across many teams and products |
Identity, authentication, authorisation
| Concept | Question | Examples |
|---|---|---|
| Identity | Who or what is this principal? | A user account, a service account, a Kubernetes workload, a device |
| Authentication (authN) | Can they prove it? | Password + MFA, passkey, mTLS certificate, signed token, workload identity |
| Authorisation (authZ) | Are they allowed to do this action on this resource now? | Roles, permissions, ownership checks, policies |
| Accounting/audit | What did they do? | Audit logs (chapter 110) |
Keep them separate in code: authentication establishes a principal (with attributes), and authorisation decisions are made per request against that principal. Most serious breaches in APIs come from authorisation bugs (A01 Broken Access Control), not broken cryptography.
Authentication
Factors
| Factor | Examples | Weaknesses |
|---|---|---|
| Something you know | Password, PIN | Phishing, reuse, credential stuffing, guessing |
| Something you have | TOTP app, hardware key, phone, passkey on a device | SMS can be SIM-swapped; TOTP codes can be phished in real time |
| Something you are | Fingerprint, face (usually unlocks a local key) | Not a secret; used locally, not sent to servers |
Multi-factor authentication (MFA) combines factors. Not all MFA is equal: SMS and TOTP codes and push approvals can be relayed by adversary-in-the-middle phishing kits (Evilginx) or defeated by "MFA fatigue" spam. Phishing-resistant MFA binds authentication to the website's origin: FIDO2/WebAuthn security keys and passkeys.
Passkeys (WebAuthn)
A passkey is a public/private key pair created per site by an authenticator (the phone's or laptop's secure hardware, a password manager, a security key):
- Registration: the site sends a challenge; the authenticator creates a key pair scoped to the site's relying party ID (its domain), keeps the private key, returns the public key.
- Login: the site sends a fresh challenge; after the user unlocks the authenticator (biometric/PIN), it signs the challenge together with the origin; the server verifies with the stored public key.
The browser includes the real origin in what's signed, so a phishing site on another domain can't obtain a usable signature. The server stores only public keys: a database leak yields nothing crackable. Passkeys sync across a user's devices via platform providers (Apple, Google, Microsoft) and password managers. Libraries: webauthn4j/Spring Security passkeys support (Java), go-webauthn (Go), py_webauthn (Python), webauthn-rs (Rust), SimpleWebAuthn (TypeScript).
Credential attacks to defend against
- Credential stuffing: reused passwords from other breaches tried at scale. Defences: MFA/passkeys, breached-password checks, rate limiting per account and per IP/ASN, bot detection, alerting on anomalous login success rates.
- Brute force: exponential backoff and temporary lockout (beware letting attackers lock out victims; prefer throttling and step-up challenges).
- Account enumeration: identical responses and timings for "unknown user" and "wrong password", and for password reset requests.
- Account recovery is often the weakest link: reset tokens must be single-use, random (≥128 bits), short-lived, stored hashed, and invalidated after use or on password change; notify the user.
Sessions and cookies
After login, the server must recognise subsequent requests. Two broad approaches:
| Server-side session | Self-contained token (JWT) | |
|---|---|---|
| What the client holds | Opaque random ID in a cookie | Signed claims |
| Server state | Session store (Redis, DB) | None needed to validate |
| Revocation | Delete the session: immediate | Hard until expiry (needs short lifetimes, deny-lists or introspection) |
| Size | Small | Larger, sent with every request |
| Good for | Browser apps, monoliths | API access tokens between services, federated identity |
For browser applications, server-side sessions with secure cookies remain the simplest robust choice.
Cookie attributes
Set-Cookie: __Host-session=Yx2…; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
| Attribute | Effect |
|---|---|
Secure |
Sent only over HTTPS |
HttpOnly |
Not readable by JavaScript (limits XSS impact) |
SameSite=Lax / Strict |
Withheld on cross-site requests (CSRF defence, chapter 108) |
__Host- prefix |
Browser enforces Secure, Path=/, and no Domain (can't be set or overridden by subdomains) |
Max-Age/Expires |
Lifetime; omit for a session cookie that ends with the browser |
Session management rules
- Generate session IDs with a CSPRNG (≥128 bits); never put user IDs or other guessable data in them.
- Rotate the session ID on login and privilege change (prevents session fixation, where an attacker plants a known ID before the victim logs in).
- Idle timeout and absolute timeout; re-authenticate for sensitive actions.
- Logout invalidates the session server-side, not just the cookie.
- Bind sessions loosely to context (detect drastic changes in device/location) without breaking legitimate mobility.
OAuth 2
What OAuth is for
OAuth 2.0 (RFC 6749) is a framework for delegated authorisation: a user (resource owner) lets a client application access their resources at a resource server (API) without giving the client their password. An authorisation server (AS) authenticates the user, obtains consent and issues access tokens scoped to what the client may do.
OAuth is not an authentication protocol by itself: an access token says "the bearer may call this API with these scopes", not "this is user X logged in to your app". OpenID Connect adds authentication on top.
The current guidance is consolidated in RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025) and the OAuth 2.1 draft (still an IETF draft in 2026), which removes the implicit and password grants, requires PKCE for all authorisation code clients, requires exact redirect URI matching, and forbids tokens in query strings.
Authorisation code flow with PKCE
Details that matter:
- PKCE (Proof Key for Code Exchange, RFC 7636): the client sends
code_challenge = BASE64URL(SHA256(code_verifier))at the start and thecode_verifierat the token step. An intercepted code is useless without the verifier. Required for public clients (SPAs, mobile, CLI) and recommended for confidential ones. state: a random value bound to the user's session, checked on return (CSRF protection for the redirect); PKCE also provides this protection when used correctly. OIDC addsnoncebound into the ID token.- Exact redirect URI matching: no wildcards, otherwise open redirects leak codes.
- Confidential clients (server-side apps) authenticate at the token endpoint with
private_key_jwtor mTLS rather than shared client secrets where possible. - The authorisation code is single-use and short-lived (seconds to a minute).
Other grants
| Grant | Use |
|---|---|
| Client credentials | Machine-to-machine: a service obtains a token for itself (no user) |
| Device authorisation (RFC 8628) | TVs, CLIs: show a code, user approves on another device (beware "device code phishing") |
| Refresh token | Obtain a new access token without user interaction |
| Token exchange (RFC 8693) | Swap one token for another: delegation/impersonation across service hops, exchanging an external identity token for a cloud credential |
| JWT bearer / assertion (RFC 7523) | Use a signed JWT (e.g. from a workload identity) as the grant |
| ~~Implicit~~, ~~Resource owner password~~ | Removed in OAuth 2.1; don't use |
Tokens
- Access tokens: short-lived (minutes to an hour), presented to APIs. Either JWTs validated locally by APIs, or opaque tokens validated by introspection (RFC 7662) at the AS. The audience (
aud) must identify the API. - Refresh tokens: long-lived, presented only to the AS. For public clients they must be sender-constrained or rotated on every use (the AS issues a new refresh token and detects reuse of old ones as theft, revoking the family).
- Scopes describe what the client may do on the user's behalf (
invoices:read), which is coarse delegation, not a full authorisation model: the API must still check that the user may access this invoice.
Browser-based apps
Storing tokens in browser JavaScript (localStorage) exposes them to any XSS. Current guidance for SPAs (IETF "OAuth 2.0 for Browser-Based Applications") favours a Backend for Frontend (BFF): a small server-side component performs the OAuth flow as a confidential client, keeps tokens server-side, and gives the browser only an HttpOnly SameSite session cookie; the BFF proxies API calls and attaches tokens.
Sender-constrained tokens
A bearer token works for whoever holds it: stolen from logs, a proxy, a compromised client or an XSS, it can be replayed. Sender-constrained tokens are bound to a key the legitimate client holds:
- mTLS-bound tokens (RFC 8705): the token contains a hash of the client's certificate (
cnf.x5t#S256); the API checks it matches the TLS client certificate. Good for service-to-service. - DPoP (RFC 9449, Demonstrating Proof of Possession): the client generates a key pair and, on each request, sends a DPoP proof: a JWT signed with its private key containing the HTTP method, URL, timestamp, a unique
jtiand a hash of the access token. The access token contains the key thumbprint (cnf.jkt). Works at the application layer, so it suits SPAs and mobile apps. Required by FAPI 2.0 security profiles in open banking (with mTLS as the alternative).
OpenID Connect
OpenID Connect (OIDC) is an identity layer on OAuth 2: the authorisation request includes scope openid, and the token response includes an ID token, a JWT asserting that the user authenticated:
{
"iss": "https://login.example.com",
"sub": "248289761001",
"aud": "my-client-id",
"exp": 1793026800, "iat": 1793023200,
"nonce": "n-0S6_WzA2Mj",
"auth_time": 1793023190,
"amr": ["pwd", "otp"],
"email": "ana@example.com", "email_verified": true
}
- The ID token is for the client, to log the user in; don't send it to APIs as an access token.
- Identify users by
iss+sub(stable, unique per issuer), not by email (emails change and can be reassigned or unverified; "email_verified" from some providers can't be trusted for account linking). - Discovery (
/.well-known/openid-configuration) and JWKS endpoints publish endpoints and signing keys. - Enterprise SSO uses OIDC or SAML 2.0; SCIM provisions and deprovisions users and groups automatically from the identity provider.
Use a certified library or framework rather than hand-rolling flows: Spring Security OAuth2 client/resource server, coreos/go-oidc + golang.org/x/oauth2, Authlib (Python), openidconnect crate (Rust), openid-client/Auth.js (Node). Identity providers: Keycloak, Auth0/Okta, Microsoft Entra ID, Google, Amazon Cognito, Zitadel, Ory.
JWTs
Structure
A JSON Web Token (RFC 7519) as JWS: base64url(header).base64url(payload).base64url(signature):
// header
{"alg": "ES256", "typ": "at+jwt", "kid": "2026-10-key-a"}
// payload
{"iss": "https://login.example.com", "sub": "user-123", "aud": "https://api.example.com",
"exp": 1793024100, "iat": 1793023200, "scope": "invoices:read", "client_id": "web-app", "jti": "6f1c…"}
The payload is only base64url-encoded, not encrypted: anyone holding the token reads it. Don't put secrets or unnecessary personal data in it (use JWE if confidentiality is required, or opaque tokens).
Validating a JWT
Classic JWT vulnerabilities:
| Bug | What happens | Fix |
|---|---|---|
alg: none accepted |
Unsigned tokens accepted | Allow-list algorithms in the verifier |
| Algorithm confusion | Server expects RS256 but accepts HS256, and verifies the HMAC using the RSA public key as the secret (which the attacker knows) | Bind each key to its algorithm; never take alg from the token to choose verification |
kid/jku/x5u injection |
Token tells the server where to fetch the key, or kid used in a SQL/file lookup |
Keys only from configured JWKS; treat kid as a lookup key in a trusted set |
Missing aud check |
A token for another API (same issuer) accepted | Check audience |
| Decoding without verifying | jwt.decode(token, verify=False) used for decisions |
Always verify |
| Weak HMAC secrets | Brute-forced offline | ≥256-bit random secrets; prefer asymmetric for multi-party |
| No revocation, long expiry | Stolen token valid for days | Short exp, refresh tokens, introspection or deny-list for high-risk |
// Spring Security resource server: validates signature (JWKS), exp/nbf, iss; add audience check
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation("https://login.example.com");
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
JwtClaimNames.AUD, aud -> aud != null && aud.contains("https://api.example.com"));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer("https://login.example.com"), audience));
return decoder;
}
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(a -> a
.requestMatchers(HttpMethod.GET, "/invoices/**").hasAuthority("SCOPE_invoices:read")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
// Go: github.com/golang-jwt/jwt/v5 with a JWKS keyfunc (e.g. github.com/MicahParks/keyfunc/v3)
jwks, err := keyfunc.NewDefaultCtx(ctx, []string{"https://login.example.com/.well-known/jwks.json"})
if err != nil { return err }
claims := jwt.MapClaims{}
tok, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
jwt.WithValidMethods([]string{"ES256", "RS256"}), // algorithm allow-list
jwt.WithIssuer("https://login.example.com"),
jwt.WithAudience("https://api.example.com"),
jwt.WithExpirationRequired(),
jwt.WithLeeway(30*time.Second))
if err != nil || !tok.Valid { return errUnauthorized }
# Python: PyJWT with JWKS
import jwt
jwks = jwt.PyJWKClient("https://login.example.com/.well-known/jwks.json")
key = jwks.get_signing_key_from_jwt(raw)
claims = jwt.decode(raw, key.key,
algorithms=["ES256", "RS256"], # never omit
audience="https://api.example.com",
issuer="https://login.example.com",
options={"require": ["exp", "iat", "sub"]},
leeway=30)
// Rust: jsonwebtoken crate
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
let header = decode_header(raw)?;
let key: &DecodingKey = jwks_cache.get(header.kid.as_deref().ok_or(AuthError)?)?; // trusted keys only
let mut v = Validation::new(Algorithm::ES256); // the key's algorithm, not the token's choice
v.set_issuer(&["https://login.example.com"]);
v.set_audience(&["https://api.example.com"]);
v.leeway = 30;
let data = decode::<Claims>(raw, key, &v)?; // checks signature, exp, iss, aud
// TypeScript: jose
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://login.example.com/.well-known/jwks.json"));
const { payload } = await jwtVerify(raw, JWKS, {
issuer: "https://login.example.com",
audience: "https://api.example.com",
algorithms: ["ES256", "RS256"],
clockTolerance: 30,
});
Authorisation models
Where authorisation happens
Authorisation must be enforced server-side on every request, at the resource being accessed. Hiding a button in the UI is not authorisation.
Broken object-level authorisation (BOLA/IDOR) is the most common API vulnerability: the API authenticates the user but doesn't check that this object belongs to them:
# ✗ IDOR: any logged-in user can read any invoice by changing the ID
@app.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: int, user = Depends(current_user)):
return db.get(Invoice, invoice_id)
# ✓ Scope the query to what the user may access (and return 404 to avoid confirming existence)
@app.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: int, user = Depends(current_user)):
inv = db.scalar(select(Invoice).where(Invoice.id == invoice_id, Invoice.tenant_id == user.tenant_id))
if inv is None or not can(user, "read", inv):
raise HTTPException(404)
return inv
// Spring: method security with a domain-aware check
@GetMapping("/invoices/{id}")
@PreAuthorize("@invoiceAuthz.canRead(authentication, #id)")
public InvoiceDto get(@PathVariable UUID id) { return service.get(id); }
@Component("invoiceAuthz")
class InvoiceAuthz {
boolean canRead(Authentication auth, UUID id) {
return repo.findTenantId(id).map(t -> t.equals(tenantOf(auth))).orElse(false);
}
}
// Go: load scoped by tenant, then check the permission
func (h *Handler) GetInvoice(w http.ResponseWriter, r *http.Request) {
p := auth.PrincipalFrom(r.Context())
inv, err := h.store.InvoiceForTenant(r.Context(), p.TenantID, r.PathValue("id"))
if errors.Is(err, store.ErrNotFound) || !h.authz.Allowed(p, "invoice:read", inv) {
http.NotFound(w, r)
return
}
writeJSON(w, inv)
}
Multi-tenant systems add a structural safeguard: tenant isolation at the data layer (tenant ID in every query via a repository abstraction, PostgreSQL row-level security policies, separate schemas or databases for high-isolation tenants).
RBAC, ABAC, ReBAC
| Model | Decision based on | Strengths | Weaknesses |
|---|---|---|---|
| ACL | Per-resource lists of who may do what | Simple, direct | Hard to manage at scale |
| RBAC (role-based) | User → roles → permissions (editor can document:write) |
Easy to understand and audit | Role explosion; can't express "own documents only" without extra checks |
| ABAC (attribute-based) | Attributes of subject, resource, action, environment (user.dept == doc.dept && time in business hours) |
Fine-grained, contextual | Harder to audit ("who can access X?") |
| ReBAC (relationship-based) | Graph of relationships (user is member of team which is editor of folder that is parent of doc) |
Natural for sharing, hierarchies, multi-tenant SaaS | Needs a graph store and consistent tuples |
Google's Zanzibar paper (2019) described the ReBAC system behind Drive, YouTube and Calendar sharing; it inspired OpenFGA (CNCF), SpiceDB (AuthZed), Permify and Ory Keto.
Policy engines
Instead of scattering if statements, externalise authorisation logic into a policy engine: the application asks "may principal P do action A on resource R?" and enforces the answer (PEP: policy enforcement point; PDP: policy decision point).
- OPA (Open Policy Agent, CNCF graduated) with the Rego language: general-purpose (APIs, Kubernetes admission via Gatekeeper, Terraform plans, CI).
- Cedar (open-sourced by AWS, used by Amazon Verified Permissions): a purpose-built, analysable language combining RBAC and ABAC, with formal verification of the engine.
- OpenFGA / SpiceDB: ReBAC with relationship tuples and a schema.
// Cedar policy: editors of a document's folder may edit it, unless the document is locked
permit (
principal,
action == Action::"edit",
resource is Document
) when {
principal in resource.folder.editors
} unless {
resource.locked
};
# OPA / Rego (v1 syntax): tenant isolation plus role permission
package invoices.authz
default allow := false
allow if {
input.action == "read"
input.resource.tenant_id == input.subject.tenant_id
"billing_viewer" in input.subject.roles
}
# OpenFGA model (DSL): ReBAC for folders and documents
model
schema 1.1
type user
type folder
relations
define owner: [user]
define editor: [user] or owner
define viewer: [user] or editor
type document
relations
define parent: [folder]
define viewer: [user] or viewer from parent
define editor: [user] or editor from parent
Practical guidance:
- Deny by default. Every endpoint requires an explicit decision; test that unauthorised users get 403/404.
- Enforce near the data (service layer or query), not only at the gateway; the gateway checks coarse things (authenticated, scope), the service checks object-level permissions.
- Filter lists, not just single fetches:
GET /invoicesmust only return permitted invoices (policy engines offer partial evaluation or "list objects" queries for this). - Write authorisation tests for each role and for cross-tenant access, and log decisions for audit.
Workload identity and short-lived credentials
Identities for software
Services need identities too: a payment service calling the ledger, a CI job deploying to the cloud, a pod reading from S3. The legacy approach is long-lived shared secrets (API keys, cloud access keys in environment variables, passwords in config): they leak through Git, logs, images and laptops, are rarely rotated, and can't be tied to a specific workload.
Workload identity gives each workload a verifiable identity issued by the platform, exchanged for short-lived credentials:
Examples:
- Kubernetes: projected service account tokens (audience-bound, time-limited OIDC JWTs) federated to cloud IAM: EKS Pod Identity / IRSA, GKE Workload Identity Federation, AKS Workload Identity (Vol. 7 ch. 89).
- CI/CD: GitHub Actions, GitLab CI and others issue OIDC tokens per job (
sub: repo:org/app:ref:refs/heads/main); cloud trust policies allow role assumption only for specific repositories, branches or environments. No cloud keys in CI secrets. - SPIFFE/SPIRE: a vendor-neutral standard for workload identity (
spiffe://example.org/ns/payments/sa/api), issuing short-lived X.509 SVIDs for mTLS between services or JWT-SVIDs; used by service meshes (Istio) and directly. - Cloud-native: instance roles/managed identities give VMs and functions credentials via the metadata service.
Service accounts and least privilege
- One identity per workload, never shared across services or environments.
- Grant the minimum permissions for its job; review with access analysers (IAM Access Analyzer, GCP Policy Intelligence recommendations).
- Prefer short-lived credentials everywhere: database credentials from Vault's dynamic secrets or IAM database authentication; SSH certificates instead of static keys; human access via SSO with just-in-time elevation.
- Where static secrets remain, keep them in a secrets manager with rotation, inject at runtime, and scan for leaks.
Propagating identity across services
When service A calls service B on behalf of a user, B needs to know both which service is calling (workload identity via mTLS or a client-credentials token) and on whose behalf (the user context). Options: forward the user's access token (only if its audience includes B), or token exchange (RFC 8693) at the AS for a new, narrower token for B carrying act (actor) claims, or internal signed context headers set only by a trusted gateway (and stripped from external requests). Never trust identity headers like X-User-Id that an external client could set.
Lab: tokens and authorisation, tested
PyJWT 2.15 with Ed25519 keys from cryptography, and small Python models of an orders API, on the lab machine. Each experiment is written as checks you can lift into a test suite.
Experiment 1: a token-validation test matrix
valid token ACCEPT sub=user-42 scope=orders:read
expired 10 min ago REJECT ExpiredSignatureError
audience billing-api REJECT InvalidAudienceError
issuer evil.test REJECT InvalidIssuerError
payload edited, old signature REJECT InvalidSignatureError
signed by a different key REJECT InvalidSignatureError
alg=none (unsigned) REJECT InvalidAlgorithmError
The decode call that produced it:
jwt.decode(token, public_key, algorithms=["EdDSA"],
audience="orders-api", issuer="https://id.tiffin.test", leeway=30)
Every row is a test your API should have. Libraries make each check easy and every omission silent: drop audience= and the billing token is accepted; accept the token's own alg header and the unsigned token gets through. leeway=30 tolerates clock skew between servers without making expiry meaningless. In production the public key comes from the issuer's JWKS endpoint, cached and refreshed by kid, so the issuer can rotate keys without breaking you.
Experiment 2: PKCE end to end
code_verifier (kept by the app): 64 chars from secrets.token_urlsafe
code_challenge (sent first) : 8tNUSC70rvC8mHXZlWsOMVLOWfwwMmLKq6uS9uXo7IY
server check at token exchange : True
stolen code + guessed verifier : False
challenge = BASE64URL(SHA256(verifier)) without padding, as RFC 7636 specifies. OAuth 2.1 and current best practice (RFC 9700) require PKCE for every client, confidential ones included, and drop the implicit and password grants entirely.
Experiment 3: the one-line fix for BOLA
owner check OFF: user-42 → order 101: 200, order 102: 200
owner check ON : user-42 → order 101: 200, order 102: 404
A valid token proves identity, not ownership. The durable fix is structural: load objects through a repository that always scopes by the caller (where id = ? and owner_id = ?), so forgetting the check becomes impossible rather than a code-review catch. Test it with two users: user A creates an object, user B requests it, assert 404.
Experiment 4: RBAC versus ReBAC
RBAC: asha may update-status of ANY order: True
ReBAC: asha may update order:101 (her kitchen): True
ReBAC: after order moves to blr-1: False
The ReBAC model stores tuples like (order:101, kitchen, kitchen:hyd-1) and (kitchen:hyd-1, member, asha), then evaluates "updater = member of the order's kitchen". OpenFGA, SpiceDB and Google Zanzibar work this way at scale, with a consistency token so a check never uses relationships older than the change that should have revoked access.
Try it yourself
- Add a
nbf(not before) claim one minute in the future and check how PyJWT andleewaytreat it. - Generate an HS256 token whose secret is your public key's PEM, and confirm
algorithms=["EdDSA"]refuses it. Why is mixing symmetric and asymmetric algorithms on one endpoint dangerous? - Write the BOLA test for your own API: two users, one object, assert the second user gets 404.
- Model "a customer may cancel their own order only while status is placed" in RBAC, ReBAC and ABAC. Which is cleanest?
Revision sheet: identity and access
Key ideas
- Authentication ≠ authorisation; check both, server-side, on every request.
- Factors: something you know, have, are; passkeys (WebAuthn) are phishing-resistant because the credential is bound to the origin.
- Sessions: random server-side IDs in HttpOnly, Secure, SameSite cookies; rotate on login; expire idle and absolute.
- OAuth 2: authorisation code + PKCE for users, client credentials for services, device flow for TVs/CLIs, token exchange for delegation. OIDC adds the ID token and user identity.
- JWT validation: signature, fixed algorithms,
exp/nbf,iss,aud; keys from JWKS bykid. - Tokens: short-lived access tokens, rotating refresh tokens, sender-constrained (DPoP, mTLS) where theft matters.
- Models: RBAC (roles), ABAC (attributes and conditions), ReBAC (relationships); policy engines OPA, Cedar, OpenFGA.
- Workload identity: short-lived credentials from the platform (SPIFFE, cloud IAM roles), no long-lived secrets.
Numbers to remember
- Lab: 7-row validation matrix, 1 accept and 6 rejects, each with a distinct error.
- PKCE verifier 43–128 characters; challenge = BASE64URL(SHA-256(verifier)).
- Access-token lifetimes are typically minutes (5–60), refresh tokens hours to days with rotation.
- OWASP API Security Top 10 (2023): API1 is Broken Object Level Authorisation.
Pitfalls
- Decoding a JWT without verifying it, or trusting its
algheader. - Skipping
aud, so tokens for one service open another. - Storing tokens in localStorage where any XSS can read them.
- Authorising by role but never by object ownership (BOLA).
- Long-lived API keys and service-account keys in repos.
- Revocation assumed for JWTs that are valid until
exp.
Glossary
- IdP: identity provider issuing tokens.
- Scope: what a token permits (e.g.
orders:read). - PKCE: proof key binding an authorisation code to the client that requested it.
- JWKS: the issuer's published set of public keys.
- BOLA / IDOR: accessing another user's object by changing its identifier.
- DPoP: proof-of-possession binding a token to a client key.