Skip to content
Tech Interview Prep
Technical interview guide

SSO & Federation Protocols (SAML, OIDC)

How a user authenticates once with an identity provider and gets trusted access across many applications.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v6
Editorial status
Reviewed

Scope: OIDC Core 1.0, OAuth 2.0 with RFC 9700 BCP, SAML 2.0, SCIM 2.0, and NIST SP 800-63C-4 guidance current 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain OAuth, OIDC, SAML, SSO, and SCIM without conflating them.

Answer

The 90-second answer

These five are not alternatives; they sit at different layers. SSO is an outcome: one login reused across apps. Federation is the trust mechanism that makes cross-domain SSO possible. SAML and OIDC are two protocols that carry authentication across that trust boundary. OAuth is not authentication at all: it delegates API access. SCIM is a separate provisioning protocol that manages the account lifecycle. A real enterprise stack runs all of them: OIDC or SAML for login, OAuth for API calls, SCIM to create and delete the accounts.

OAuth 2.0: delegation, not identity

Authorization code flow with PKCE (RFC 6749 + RFC 7636):

  1. Client generates a code_verifier (43–128 chars) and sends its SHA-256 hash as code_challenge on /authorize.
  2. User authenticates at the authorization server; it redirects back with a single-use code, valid ~30–60s.
  3. Client POSTs code + code_verifier to /token; the AS re-hashes and compares, then returns an access token (and usually a refresh token).
  4. Client calls the resource server with Authorization: Bearer <token>.

Nothing here says who the user is. The access token is for the API, not for the client to read.

OIDC: authentication layered on OAuth

The /token response also carries an ID token: a JWT signed by the AS, usually RS256. The client validates signature against the AS's JWKS from /.well-known/openid-configuration, then iss, aud == its client_id, exp, and the nonce it sent. Only then does it treat the subject as authenticated.

SAML 2.0: the same job in XML

SP-initiated: SP sends an AuthnRequest, IdP authenticates, returns a signed Response containing an Assertion with Subject, Conditions (NotBefore/NotOnOrAfter, typically a 5-minute window), AudienceRestriction, and AttributeStatement. The SP validates the XML-DSig signature, audience and time window, then creates its own session.

SCIM 2.0: lifecycle (RFC 7643/7644)

REST + JSON: POST /Users, PATCH to deactivate, DELETE, filter=userName eq "...". Okta and Entra ID push changes here.

CarriesFormatTypical use
OAuth 2.0AuthorizationJSONAPI access
OIDCAuthenticationJWTWeb/mobile login
SAML 2.0AuthenticationXMLEnterprise browser SSO
SCIM 2.0ProvisioningJSONAccount/group lifecycle
SSOSession reuse—Outcome, not a protocol

Trade-offs

Pick OIDC for new builds: JSON, discovery, mobile/SPA, API-friendly. Pick SAML when the IdP only speaks SAML or you're integrating legacy enterprise apps. Many IdPs do both against the same directory, so you can run both.

Failure modes

  • Confused deputy: client accepts an access token as proof of identity. Detect by enforcing the ID token aud check; never use an access token for auth.
  • Skipped ID token validation → replay. Reject alg=none and unverified signatures.
  • SAML XML signature wrapping: validate the signature over the specific assertion element, not the whole document.
  • SCIM deprovisioning lag: SCIM only removes access if the RP honors it. Detect by reconciling IdP active users against app accounts.
  • Global logout: SAML SLO is unreliable and OIDC back-channel logout is spotty; RP sessions outlive the IdP session.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design an OIDC authorization code flow with PKCE.

Answer

Assumptions: a public client (SPA or native app) that cannot keep a client secret, and an IdP that supports OIDC Core 1.0 and RFC 7636. If the client is confidential, PKCE is still recommended: OAuth 2.1 requires it for all authorization-code clients, but you also authenticate with a secret or private_key_jwt.

Core answer: the client generates a PKCE verifier (43–128 characters from the unreserved set), derives challenge = BASE64URL(SHA256(verifier)), and sends challenge plus method=S256, state and nonce to the authorization endpoint. The user authenticates at the IdP, which redirects to the exact registered redirect_uri with code and state. The client checks state, then POSTs code and verifier to the token endpoint over TLS. The IdP verifies SHA256(verifier) == challenge, checks the code is unused and within its lifetime (RFC 6749 recommends a maximum of 10 minutes), and returns an ID token and access token. The client validates the ID token (signature via JWKS, iss, aud, exp/iat with a small skew, nonce, at_hash) then rotates the local session id and deletes the transaction state.

Why state and nonce are separate: state protects the redirect leg. It binds the callback to the browser session that started the flow, so an attacker cannot feed a victim's browser an authorization response for the attacker's account (login CSRF). nonce protects the token leg. It goes into the ID token and the client checks it matches the value it sent, so an attacker cannot replay an ID token from another session. PKCE protects the code exchange: an attacker who intercepts the code (for example a malicious app registered for the same custom scheme on mobile) cannot redeem it without the verifier, which never leaves the client. S256 is required over plain because plain sends the verifier in the authorize request, where it can be read.

Why rotate the session id: session fixation. If the pre-login session id is known to an attacker, they can fix it and then ride the authenticated session. Rotate after successful login.

PKCE generation, Python 3.12:

Python
import base64, hashlib, secrets

def pkce_pair():
    verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode("ascii")).digest()
    ).rstrip(b"=").decode()
    return verifier, challenge

v, c = pkce_pair()
print(len(v), len(c), c == base64.urlsafe_b64encode(hashlib.sha256(v.encode()).digest()).rstrip(b"=").decode())

Trace: token_bytes(32) → 32 bytes. urlsafe_b64encode → 44 characters with one '=' padding; rstrip removes it → 43 characters, inside the 43–128 range. sha256 of the 43-character ASCII verifier → 32-byte digest; base64url → 44 characters, rstrip → 43. Output: 43 43 True.

Flow trace with hypothetical values:

stepactionvalue
1client generatesverifier = 43 chars, challenge = S256(verifier), state = 32 random bytes, nonce = 32 random bytes
2GET /authorizeresponse_type=code, client_id=web-app, redirect_uri=https://app.example/cb, scope=openid profile, state, nonce, code_challenge, code_challenge_method=S256
3IdP redirectshttps://app.example/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=...
4client checks statematches stored state; else abort
5POST /tokengrant_type=authorization_code, code, redirect_uri, client_id, code_verifier
6IdP checksSHA256(verifier) == challenge; code unused and < 10 min old; returns ID token + access token
7client validates ID tokensignature via JWKS, iss, aud, exp/iat ± 60 s, nonce, at_hash
8client rotates sessionnew session id, delete transaction state

ID token validation:

claimcheckwhy
issequals expected issuertoken from another IdP
audcontains client_idtoken for another client
exp/iatnow within [iat − 60 s, exp + 60 s]clock skew
nonceequals sent noncereplay
at_hashleft half of SHA-256(access_token) matchesbinds access token to ID token
signatureverify with JWKS; reject alg=none and HS256 for public clientsforgery

Failure modes and detection:

  • State mismatch → abort, log, alert on rate. Indicates login CSRF or a stale tab.
  • Nonce mismatch → abort. Indicates replay or a misconfigured client.
  • Code replay → IdP returns invalid_grant. Client must not retry with the same code.
  • Clock skew too tight → valid tokens rejected; monitor token validation failures. Too loose → expired tokens accepted.
  • Redirect URI wildcard or open redirect → code leakage; audit registered URIs and require exact match.
  • Missing PKCE on a public client → code interception; enforce S256 at the IdP.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare state, nonce, and PKCE in an OIDC login.

Answer

What a strong candidate says first

All three are per-transaction values you generate before redirecting to the IdP and verify on the way back, but they bind different things and stop different attacks. State binds the callback to the browser session that started the login. Nonce binds the ID token to that same request. PKCE binds code redemption to the client instance that holds the verifier. A code flow needs all three; none substitutes for another.

StateNoncePKCE
Bindscallback to the browser sessionID token to the auth requestcode redemption to the client instance
Travels inauth request, returned in redirect queryauth request, returned as nonce claim in the ID tokencode_challenge in auth request, code_verifier at token endpoint
Stopslogin CSRF / injected authorization responseID token replay or injectioncode interception or injection
Storedserver-side session (or SameSite=Lax cookie)server-side sessionserver-side session
Requiredalways in code flowrequired in implicit/hybrid, recommended in code flowrequired for public clients; RFC 9700 recommends it for confidential clients too

Mechanism, in one callback

Python
# Authorization request, once per login
verifier  = b64url(os.urandom(32))                 # 43 chars
challenge = b64url(sha256(verifier.encode()).digest())
state, nonce = b64url(os.urandom(32)), b64url(os.urandom(32))
session.update(pkce=verifier, state=state, nonce=nonce)
params = {"response_type": "code", "client_id": CLIENT_ID,
          "redirect_uri": REDIRECT_URI, "scope": "openid profile",
          "state": state, "nonce": nonce,
          "code_challenge": challenge, "code_challenge_method": "S256"}

# Callback
if not hmac.compare_digest(request.args["state"], session.pop("state")):
    abort(400)                                     # login CSRF / stale callback
tokens = token_endpoint(code=request.args["code"],
                        code_verifier=session.pop("pkce"),
                        client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
claims = jwt.decode(tokens["id_token"], jwks, algorithms=["RS256"],
                    audience=CLIENT_ID, issuer=ISSUER)
if not hmac.compare_digest(claims["nonce"], session.pop("nonce")):
    abort(400)                                     # ID token replay / injection

session.pop is the consume-once step: a replayed callback finds no stored value and fails. In hybrid flows the ID token also carries c_hash and at_hash, which bind the code and access token to the ID token; nonce does not cover those.

Failure modes and how you see them

  • State not verified, or verified against a value not tied to the session. Login CSRF: the attacker authenticates as themselves, captures the callback URL, and gets the victim to open it. The victim's browser now holds the attacker's session, so everything the victim does lands in the attacker's account. Detect by counting state-validation failures; a steady nonzero rate is either stale tabs or an attack.
  • Nonce not verified. An ID token captured from another session (leaked token-endpoint response, log) is replayed and accepted, minting a session for the wrong subject. Detect with a nonce-mismatch counter, and alert when an ID token arrives with no nonce claim after you sent one.
  • PKCE downgrade. The server accepts an authorization request with no code_challenge, or with code_challenge_method=plain. An attacker who intercepts the code (a malicious app registered on the same custom scheme, a leaked redirect URI) POSTs it to the token endpoint and gets tokens for the victim. With S256 the token endpoint demands the verifier the attacker never saw and returns invalid_grant. Detect by rejecting requests missing code_challenge, monitoring for plain, and watching invalid_grant spikes at the token endpoint.

When each is not needed. PKCE is the one you never drop: it is the only control that survives a public client or a leaked redirect. State is unnecessary only if the callback is bound to the session by another mechanism you can prove, which in practice means you keep it. Nonce is the one you can omit in a pure code flow with a confidential client, because the code exchange already authenticates the client, but it costs one random value, so keep it unless you have a reason not to.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Define safe ID-token and access-token handling.

Answer

What I'd say first

Assumptions: OIDC authorization-code flow with PKCE, one IdP, a browser client and a handful of resource servers, JWT access tokens. If your access tokens are opaque, the split below is unchanged: only the validation step moves from local signature checking to an introspection call.

The two tokens have different audiences, so they have different validation contracts. An ID token is a signed assertion to the client that authentication happened; it is validated once, at the client, and then converted into your own session. An access token is a bearer credential for resource servers; each one validates it against its own audience and scopes. Treating the ID token as a universal API credential is the bug: the format is not the issue.

ID token, at the client only

Signature against the IdP JWKS (select by kid, cache the set), iss exactly equal to the issuer, aud containing your client_id, azp equal to client_id when there are multiple audiences, exp/iat/nbf with a few seconds of clock tolerance, nonce equal to the value you generated and stored in the session, and auth_time/acr if you demanded re-authentication. Then mint your own session cookie and drop the token.

JavaScript
// Node 20, jose v5
import { createRemoteJWKSet, jwtVerify } from 'jose';

const jwks = createRemoteJWKSet(new URL('https://idp.example.com/.well-known/jwks.json'));

export async function verifyIdToken(idToken, expectedNonce) {
  const { payload } = await jwtVerify(idToken, jwks, {
    issuer: 'https://idp.example.com/',
    audience: 'web-app',
    algorithms: ['RS256'],
    clockTolerance: 5, // seconds
  });
  if (payload.nonce !== expectedNonce) throw new Error('nonce mismatch');
  return payload; // build session, then discard the token
}

Trace: a token minted with aud: "api-gateway" reaches this function. jwtVerify throws JWTClaimValidationFailed with claim: 'aud' before the nonce check runs; login is rejected and no session is created. Same token presented to the API gateway would pass there, which is exactly why the client must not accept it.

Access token, at each resource server

ID tokenAccess token
Audienceclient_idthis service's identifier
Validatedclient, once at loginevery resource server, every request
Lifetimeseconds, consumed immediately5–15 min typical
On failurereject login401, do not retry the same token

Check signature (or introspect), iss, aud equal to this service, scope covering the operation, exp, and token type. Never parse an opaque token to infer identity; if you need identity, call userinfo or read sub from a JWT you actually validated.

Trade-offs

JWT access tokens verify locally (sub-millisecond, no network hop) but revocation is hard, so you keep lifetimes short and lean on refresh. Opaque tokens with RFC 7662 introspection revoke immediately, at the cost of a round trip per request and a new hard dependency; caching introspection for 30–60 s trades revocation latency for load. Relaxing to stateless JWTs is defensible inside a mesh with mTLS and no third-party clients; it is not defensible for tokens that leave your trust boundary. If replay is the threat, bind the token to the client with DPoP (RFC 9449) or mTLS (RFC 8705) rather than shortening lifetimes further.

Failure modes and how you notice

  • Audience confusion: service B accepts a token minted for A. Detection: 401s carrying claim: 'aud' in the resource server's logs, or worse, a spike in cross-service calls with scopes B never issues. Cost: blast radius is the union of both services' scopes until the token expires.
  • Token in logs: access tokens land in access logs, APM traces, or error reports. Detection: regex the log pipeline for the eyJ JWT prefix and for Authorization: Bearer in captured headers; check browser history and Referer too. Cost: exposure for the token's full lifetime, and forced revocation.
  • ID token used as an API credential: a resource server that accepts aud == client_id accepts tokens minted for any client. Detection: alert when a resource server sees an audience that is not its own identifier.
  • Algorithm confusion: alg: none, or HS256 signed with the public key as the HMAC secret. Detection: reject anything outside an explicit algorithms allowlist and alert on unexpected alg values. Cost: full forgery of any identity.

Figures above are illustrative; measure your own introspection latency and token lifetimes before quoting them.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Implement robust OIDC ID-token validation.

Answer

Core answer (first 90 seconds)

An ID token is a JWT you verify against the issuer's published keys, and only then do you map iss + sub to a local account. Nothing in the token is trusted before that, including the kid and alg in its own header.

Assumptions I'd state up front: confidential client, authorization-code flow, ID token arrives over the back channel, and the issuer is one I configured out of band. Never one read from the token.

Order matters:

  1. Parse the header. Reject any alg that isn't the one registered for this client (id_token_signed_response_alg, normally RS256). Ignore jku, jwk, and x5u entirely.
  2. Fetch keys from the jwks_uri in https://<issuer>/.well-known/openid-configuration, cached.
  3. Verify the signature, then iss exact match, aud contains client_id, azp equals client_id when present, exp > now, iat inside a small window, nonce equal to the one you sent, and auth_time/acr if you asked for max_age.
  4. Only then look up the account by (iss, sub).
JavaScript
// jose v5+, Node 20
import { createRemoteJWKSet, jwtVerify } from 'jose';

const JWKS = createRemoteJWKSet(
  new URL('https://idp.example.com/.well-known/jwks.json'),
  { cacheMaxAge: 600_000, cooldownDuration: 30_000 } // 10 min cache, 30 s between forced refetches
);

export async function validateIdToken(token, { issuer, clientId, nonce }) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer,                 // exact string match on iss
    audience: clientId,     // aud must contain clientId
    algorithms: ['RS256'],  // pinned; the token's own alg is never honoured
    clockTolerance: 60,     // seconds of skew allowed on exp/nbf
    maxTokenAge: '5 min',   // requires iat, bounds the replay window
  });
  if (payload.azp !== undefined && payload.azp !== clientId) throw new Error('azp mismatch');
  if (nonce !== undefined && payload.nonce !== nonce) throw new Error('nonce mismatch');
  return payload; // caller maps (payload.iss, payload.sub) -> account
}

Worked trace. Header {"alg":"RS256","kid":"k2"}, payload {"iss":"https://idp.example.com","aud":"web-app","sub":"auth0|abc","exp":1735689600,"iat":1735689300,"nonce":"n-7f3a"}. Now = 1735689400.

  1. kid=k2; the cache was filled 4 min ago and holds only k1 → miss.
  2. Last fetch was 4 min ago, past the 30 s cooldown, so jose refetches once. k2 is there. Signature verifies.
  3. RS256 is in the allowed list. Had the header said HS256, jose throws before touching a key.
  4. iss matches exactly. 5. aud contains web-app. 6. exp - now = 200 s, above the −60 s tolerance. 7. now - iat = 100 s ≤ 300. 8. azp absent, nonce matches. 9. Map ('https://idp.example.com','auth0|abc') → account.

Trade-offs.

Local verification vs. skipping it. OIDC Core §3.1.3.7 lets you skip the signature check when the ID token comes straight from the token endpoint over TLS. Take that only if the token never transits the browser and is never stored; otherwise a misconfigured proxy or a token pulled from a log is accepted. Introspection (RFC 7662) is the alternative for opaque access tokens: an ID token is a JWT by definition, so there is nothing to introspect.

Strict vs. lenient iat. A 5-minute window bounds how long you must keep nonces and how long a stolen token replays; it breaks clients with skewed clocks. Hours of tolerance means hours of nonce storage. Decide by how long you retain nonces.

JWKS cache TTL. 10 minutes means few fetches but a rotation outage window; seconds means load on the IdP and a thundering herd on every unknown kid. jose's 30 s cooldownDuration is the mitigation; PyJWKClient defaults to a 300 s lifespan, nimbus RemoteJWKSet to 5 minutes.

Failure modes.

  • Algorithm confusion: an HS256 token signed with the RSA public key as the HMAC secret. Caught by pinning algorithms; the symptom is a token that verifies against a public key.
  • Header key injection: jku/x5u pointing at an attacker host. Caught by never reading them: only the discovered jwks_uri.
  • Rotation race: the IdP drops k1, every in-flight request misses, and N concurrent refetches hit the IdP. Detected as a JWKS fetch spike; bounded by the cooldown.
  • Cross-token-type confusion: an access token (typ: at+jwt) presented as an ID token. Caught by requiring aud == client_id and a matching nonce.
  • Duplicate claims: two aud or sub keys, where the verifier and the resource read different ones. Reject duplicates at parse time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Prevent JWT algorithm and cross-token confusion.

Answer

The 90-second answer. The JWT header (alg, kid, jku) is attacker-controlled and unauthenticated until verification succeeds. So the verifier must never let the token pick its own algorithm or key. Pin the accepted algorithm per key, and make each token type fail the other's validation rules. Assume you're a relying party on a third-party OIDC issuer you don't control, with a JWKS endpoint.

Why it breaks. A naive verifier reads alg from the header and dispatches on it. Take an RS256 token, re-sign it with HS256 using the issuer's public key PEM bytes as the HMAC secret, set alg: HS256. The verifier sees HS256, uses its configured key, the public key, as the HMAC secret, and the signature matches. The public key is public by design; it's in the JWKS. That's the RS256→HS256 confusion. alg: none is the same class: an unsigned token accepted because the library honoured the header.

Trace: (1) GET /.well-known/jwks.json, read the RSA public key. (2) header {"alg":"HS256","typ":"JWT"}, payload {"sub":"admin","aud":"api://orders","iss":"https://idp.example.com/"}. (3) HMAC-SHA256 over b64url(header)+"."+b64url(payload) keyed with the PEM bytes. (4) Send. Any verifier whose algorithms list includes HS256 and whose key is that PEM accepts it.

What to do. Pin exactly one algorithm per key, and select the key by kid from a JWKS you fetched from a configured URL: never from the token's jku, jwk or x5u.

Python
# PyJWT >= 2.0 — algorithms is required, and must be a single family
jwt.decode(token, public_key_pem, algorithms=["RS256"],
           audience="api://orders", issuer="https://idp.example.com/",
           options={"require": ["exp", "iat", "aud", "iss", "sub"]})
JavaScript
// jose (Node) — JWKS URL is configured, not taken from the token
const JWKS = createRemoteJWKSet(new URL("https://idp.example.com/.well-known/jwks.json"));
await jwtVerify(token, JWKS, { algorithms: ["RS256"],
  issuer: "https://idp.example.com/", audience: "api://orders" });

RFC 8725 §3.1 and §3.11 are the primary source: perform algorithm verification, use explicit typing.

Cross-token confusion. Same issuer, same key, two token types: an access token replayed as an ID token, or a token minted for another client. RFC 8725 §3.12: mutually exclusive validation rules. If you control the issuer, sign each type with a distinct key. If you don't, lean on audience and required claims.

tokenkey (illustrative)must have
ID tokenkid id-2024aud = client_id, nonce
access tokenkid at-2024aud = api://orders, scope
logout tokenkid lo-2024events, sid

Trade-offs. Distinct keys per type cost rotation coordination: every key roll touches all verifiers. Pinning one algorithm breaks issuers that rotate across families; the JWK alg field lets you pin per key instead. Strict aud validation breaks legitimate multi-audience tokens. typ is weak in practice: most issuers emit typ: JWT for everything, so it can't be the only discriminator.

Failure modes and detection. Log alg, kid and iss on every verification failure, and alert when the header alg differs from the JWKS key's alg: that's the confusion attempt. Reject none before key lookup. Any outbound fetch triggered by a token header (jku) is a red flag. Test with negative fixtures: a valid RS256 token re-signed HS256 with the public key, an alg: none token, and an access token presented to the ID-token path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Harden OIDC discovery and JWKS caching.

Answer

The answer, first 90 seconds

Assume we're the relying party, the IdP is a third party we don't control, tokens arrive through browser redirects, and we can ship config but can't change the IdP.

Pick the issuer from a deploy-time allowlist. Build the metadata URL per OpenID Connect Discovery 1.0: issuer must be HTTPS with no query or fragment, then concatenate /.well-known/openid-configuration. Fetch with zero redirects, a body cap, and the resolved IP checked against private ranges. Require the returned issuer to be byte-identical to the configured one: RFC 8414 section 3.3 says the document MUST NOT be used otherwise, and OIDC Core 1.0 section 3.1.3.7 applies the same exact match to the iss claim. Pin accepted signing algorithms from policy, never from the JWS header. Cache JWKS keyed by (issuer, kid); on an unknown kid do exactly one coalesced refetch outside the TTL; still unknown, reject.

Why each control is load-bearing

Exact issuer match. The only link between the token and the key set is the issuer string. Drop the check and anyone who can influence which issuer you discover (a redirect, a spoofed DNS answer, an unvalidated tenant field) gets you to load their metadata, which advertises their jwks_uri. Their token, their key, verifying cleanly. That is the mix-up class of attack; matching on both the discovery document and the iss claim closes it.

One refetch on unknown kid. A correct rotation publishes the new key before it signs anything, so a fresh cache never misses. You miss when your cache predates the rotation. One forced refetch, single-flighted per issuer so N concurrent requests with the same kid make one HTTP call, covers that. Unlimited refetch turns the kid header, attacker-controlled, into amplification: random kids in, HTTPS requests out, aimed at the IdP.

Cache key (issuer, kid), never kid alone. A flat kid-to-key map lets a token from issuer B verify with issuer A's key on a kid collision. Not a performance bug; a signature-verification bypass.

Worked trace: rotation

Policy: TTL = min(response Cache-Control max-age, our 3600 s cap), here 300 s. ID token lifetime 900 s.

  • t=0, fetch succeeds, cache = {k1}, expires t=300.
  • t=290, k1 signs a token with exp=1190.
  • t=300, background refresh returns {k1, k2}; retain k1.
  • t=600, refresh returns {k2} only. k1 retired at t=600, retained through t=1500 (retention >= 900 s token lifetime), so the t=290 token still verifies.
  • t=700, token signed by k3 arrives. Kid k3 unknown, so one single-flight refetch; metadata now {k2, k3}; verify. Fifty concurrent k3 tokens produce two fetches, not fifty.
  • If the t=700 fetch fails, reject k3 only. k2 tokens keep verifying from cache.

Retention shorter than the token lifetime is the difference between a rotation and a login outage.

Trade-offs

Allowlist vs dynamic discovery. For B2B SaaS where customers bring their own IdP you cannot pre-allowlist. Then you need per-tenant registration with verified domain control (DNS TXT or a signed metadata document), the same SSRF controls, and per-tenant cache isolation. The exact-match rule never relaxes: only the list of issuers does.

Lazy refetch vs background refresh at TTL/2. Background refresh keeps the round trip off the login path but forces you to retain retired keys; lazy-only is simpler and puts the IdP's latency directly into your validation path. Run both.

Honor Cache-Control vs hard local cap. TTL must be min(response max-age, your cap): a hostile or sloppy IdP sends max-age=31536000 and pins you to a revoked key. Short TTL costs fetches and gives an unreachable IdP more chances to break logins. 300 s to 3600 s is the usable band.

Fail closed vs stale-on-error. Fail closed on unknown kid. But an in-memory-only cache plus a restart during an IdP outage breaks every login, so persist last-good JWKS to disk: you then fail only for genuinely unknown keys.

Failure modes to watch

  • Unknown-kid rejections climbing: key retention shorter than token lifetime.
  • Refetch rate per issuer climbing: someone is streaming bogus kids, or single-flight is missing.
  • Login p99 tracking the IdP's p99: the fetch is happening inline on the validation path. Keep separate hit and miss latency histograms.
  • Same-origin checks on jwks_uri breaking real IdPs: issuers routinely serve keys from a different host. Allowlist hosts per issuer instead.
  • SSRF through a redirect to a link-local address: zero redirects, and validate the resolved IP rather than the hostname, since the hostname can be re-resolved between check and connect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Plan SAML and OIDC signing-key rotation.

Answer

Core answer

Assume you control the IdP and are rotating the key that signs SAML assertions and OIDC id_tokens; the SPs are relying parties you cannot coordinate a flag day with. The rule is publish-then-sign, overlap, drain, retire: never sign with a key before every relying party can verify it, and never remove a verification key until the last artifact it signed has expired everywhere. Ordinary rotation is a scheduling problem. Compromise is an invalidation problem, and the two have different runbooks.

Why the two protocols differ

SAML anchors trust in metadata: md:KeyDescriptor use="signing" inside md:IDPSSODescriptor, fetched from a pinned metadata URL. Metadata carries certificates, not key IDs: the SP tries each signing key. It also carries validUntil (absolute timestamp) and cacheDuration (ISO 8601 duration), which bound how long an SP may hold a stale copy.

OIDC anchors trust in jwks_uri from the discovery document. The JWKS is a JWK Set (RFC 7517); each key has a kid, and the verifier selects by the kid in the JWT header. An unknown kid should trigger one rate-limited refetch, not a scan of every key.

The sequence, with numbers

Take a labelled hypothetical: longest metadata cache C_max = 24 h, longest assertion/id_token lifetime L = 5 min, clock skew S = 5 min. OIDC Core permits "a few minutes" of leeway for exp/iat/nbf, so 5 min is a defensible S.

whenactionwhy
t0publish new public key next to oldSPs with cached metadata need a full cache period to see it
t0 + C_maxstart signing with new keyevery SP has refetched at least once
t0 + C_max + L + Sremove old public keylast old-signed artifact has expired, plus skew
after thatdestroy old private keynothing can still require it

Total overlap ≈ 24 h 10 min. C_max is min(cacheDuration, validUntil − now): a short validUntil forces an earlier refetch and shortens the window.

JWKS during overlap:

JSON
{"keys":[
 {"kty":"RSA","use":"sig","alg":"RS256","kid":"2025-05","n":"...","e":"AQAB"},
 {"kty":"RSA","use":"sig","alg":"RS256","kid":"2024-11","n":"...","e":"AQAB"}
]}

Both kids present; verifiers pick by header kid. In SAML the equivalent is two KeyDescriptor use="signing" elements, matched by certificate.

Failure modes

  • Signing before publication: SPs with cached metadata reject with signature-validation failure. Detect as a spike in SP/client-side validation errors: SAML SPs log a signature error, OIDC clients log id_token validation failure.
  • Retiring too early: in-flight old-signed assertions fail right after removal. Detect as a burst of failures in the minutes after the retirement step.
  • Unknown-kid refetch storm: verifiers that refetch JWKS on every unknown kid without rate limiting turn rotation, or an attacker sending random kids, into a DoS on jwks_uri. Cache and rate-limit.
  • Token-controlled key URLs: never fetch a key from jku, x5u or an embedded jwk in the token header. RFC 8725 (JWT BCP) calls these out; pin the metadata/JWKS source.
  • alg confusion: reject alg: none and do not let the token choose the algorithm family (RS256 vs HS256). RFC 8725 again.
  • Understated skew: artifacts fail at the boundary; S must cover the worst clock in the fleet.

Compromise

Overlap does not help here. Publish the new key, remove the compromised one immediately, and accept that in-flight artifacts fail. You cannot revoke an issued SAML assertion: the exposure window is SessionNotOnOrAfter (or SLO), so shorten it and force re-auth. For OIDC, revoke refresh tokens and shorten exp; already-issued access tokens stay valid until exp unless you have introspection or a denylist.

What changes the decision

If you can push metadata to every SP, or all SPs cache for minutes, the overlap collapses. If any SP hardcodes the certificate and never refreshes metadata, you need a coordinated manual cutover: the one case where a flag day is unavoidable. If you have introspection or a token denylist, compromise recovery is bounded by that, not by exp.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Harden OIDC redirects and post-login navigation.

Answer

Assumptions: confidential web client, one IdP, authorization code + PKCE (S256), server-side session. If you're a native app, the loopback rule below replaces the exact-match rule.

The answer. Register the full callback URL per environment and per client, https://app.example.com/auth/callback, and have the authorization server compare it with exact string equality. No wildcards, no prefix match, no "any subdomain of example.com". The one exception the specs carve out is native apps on the loopback interface (RFC 8252 §7.3): http://127.0.0.1:{port}/cb, where the AS must accept any port because the OS picks an ephemeral one. Everything else is exact.

Then keep the return path out of the URL entirely. state is a CSRF token, not a routing table. On /login, mint 16 random bytes, store {state → {returnPath, nonce, code_verifier}} server-side with a 10-minute TTL, and set it as an HttpOnly, Secure, SameSite=Lax cookie. After the callback, look up the state, delete it (single use), and redirect to the stored path: validated as a local path: starts with /, not //, not /\.

Why prefix matching is exploitable. https://app.example.com@evil.com/cb has host evil.com; app.example.com is userinfo. A startsWith("https://app.example.com") check passes it and the code lands at the attacker. Same for https://app.example.com.evil.com/cb under a suffix match, and https://app.example.com/cb/../../evil under a path-prefix match. Exact match kills all three. Wildcards are worse: *.example.com means a subdomain takeover on any forgotten host, an expired CNAME to a deprovisioned app, hands over codes.

Why the server-side transaction beats a signed return path. You can sign the return path and carry it in state, but then the redirect target is attacker-influenced input you must re-validate on every hop, and one validation bug is an open redirector. The store makes the target a server-side lookup: the client can only choose from what you already wrote. Cost: a single Redis GET (sub-millisecond on the same host), a TTL/cleanup story, and two tabs racing on the same state. Key the store by state, not by session, so each tab gets its own.

Trade-offs.

choicestrict optionwhat it costs you
redirect_uri matchexact stringevery preview deploy needs its own registration, or a stable proxy host
return pathserver-side storeRedis dependency, TTL, per-tab keys
response_modeform_postcode never in URL/history/Referer, but the callback must accept POST
session cookieSameSite=LaxStrict drops the cookie on the IdP's cross-site GET callback

Failure modes and how you see them.

  • Referer leak: the callback page loads analytics, so ?code= rides along in the Referer. Fix: callback is a 302 to a clean URL, Referrer-Policy: no-referrer, Cache-Control: no-store. Detect: grep access and analytics logs for code=.
  • X-Forwarded-Host injection: you rebuild redirect_uri from the request host and an attacker sends X-Forwarded-Host: evil.com. Fix: pin PUBLIC_ORIGIN in config; the proxy overwrites the header, never appends. Detect: assert the redirect_uri host equals the pinned origin, alert on mismatch.
  • Mix-up: validate the iss parameter in the authorization response (RFC 9207) against the expected issuer.
  • Code replay: the AS returns invalid_grant on second use (RFC 6749 §4.1.2). Detect: alert on repeated invalid_grant for one code.
  • Open redirector: alert on any post-auth 302 whose Location host differs from the app host.

Post-logout. post_logout_redirect_uri is a separate allowlist with its own exact match, and the OP should require id_token_hint so it can't be used as an open redirector. Validate it independently of the login callback: sharing one matcher between the two is how a logout link becomes the leak.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Review a PKCE implementation for downgrade and verifier risks.

Answer

Assumptions first. This is a public client (mobile or SPA, no client secret) on the authorization code flow, and the authorization server is one you configure, not one you trust blindly. The review has three questions: does the AS require a verifier whenever it stored a challenge, is S256 the only accepted method, and is the verifier fresh, high-entropy, single-use and never logged.

What PKCE actually buys you. The code is a bearer token sitting in the redirect. PKCE makes it a proof-of-possession: the client sends code_challenge = BASE64URL(SHA256(ASCII(code_verifier))) on the authorization request, the AS stores it alongside the code, and at redemption recomputes it from the verifier. RFC 7636 fixes the verifier at 43–128 characters from the unreserved set [A-Za-z0-9-._~]; 32 random bytes base64url-encoded is exactly 43 characters and 256 bits, which is the shape you want. An intercepted code is then useless without the verifier.

Downgrade paths, and where each one is stopped.

  1. Strip code_challenge from the authorization request. The AS issues a code with no challenge, and the code is a bearer token again. The token-endpoint rule "reject a verifier-less redemption when a challenge was stored" does not catch this: there was no challenge to store. The only defense is the AS refusing authorization requests from public clients that omit PKCE. That is a configuration decision, and it is the first thing to verify.
  2. Strip code_verifier from the token request. Now the AS-side check does the work: if a challenge was stored, a missing verifier is invalid_grant, full stop.
  3. Downgrade the method to plain. With plain the challenge equals the verifier, so anyone who saw the authorization request has the secret. RFC 7636 §4.3 defaults code_challenge_method to plain when the parameter is absent, so stripping just that one parameter is enough. Require the parameter explicitly or default it to S256. RFC 9700 (January 2025) makes S256 the required method and drops plain.

Verifier risks. Reuse is the quiet one: if the client generates one verifier and reuses it across authorization requests, a single leak compromises every code. Fresh per request. Leakage is the other: the verifier must never reach access logs, the Referer header, crash reports, or a redirect. And the AS must bind the verifier to that specific code and make the code single-use, or a replayed redemption succeeds.

The check itself, AS side:

Python
record = codes.pop(code)                 # single-use: pop, not get
if record is None:
    return error("invalid_grant")
if record.challenge is not None:
    if verifier is None:
        return error("invalid_grant")    # token-request downgrade
    if record.method != "S256":
        return error("invalid_grant")    # plain not accepted
    if b64url(sha256(verifier.encode("ascii"))) != record.challenge:
        return error("invalid_grant")

Note the fall-through: a code issued without a challenge is accepted with no verifier. That is exactly why path 1 has to be closed at the authorization endpoint, not here.

Detection in production. Count invalid_grant by reason at the token endpoint. A spike in "missing verifier" or "plain" is an active downgrade attempt, not user error: alert on it. On the client, assert that each authorization request carries a distinct verifier and that the verifier never appears in the log pipeline; grepping a day of logs is a cheap check.

Trade-offs. Plain vs S256: plain only ever existed for constrained clients that cannot compute SHA-256; if you have one, isolate it, because it gives you almost nothing. Verifier length vs usability: 43 characters is the floor and there is no reason to go shorter. It is generated, not typed. Client-side vs AS-side enforcement: you need both, but the AS-side check is the one that matters, because the client is the thing you are defending against.

Framework defaults worth knowing. Spring Security 5.2+ enables PKCE with S256 by default for public clients (those registered without a client secret); AppAuth on iOS and Android defaults to S256. If your review finds plain in use, it is a deliberate override, not a default.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Secure a relying party that supports many OIDC providers.

Answer

What I'd say first (60–120s)

Assume one RP service fronting N providers, call it 5 to 40, each with its own client registration, and a callback URL we control. The core answer: never let the request decide which issuer you trust. Every login transaction gets a server-side record that pins the issuer, and every token response is validated against that pinned issuer before any token endpoint call or key lookup. Discovery, redirect targets and key sets come from configuration, never from login hints or token fields.

Why: the mix-up attack

With two providers A and M, an attacker who controls M can start a flow at A, then hand the RP an authorization response that looks like M's. If the RP picks the token endpoint from the response, it sends A's code to M, which forwards it to A and gets a valid token for the victim. RFC 9207 adds an iss parameter to the authorization response so the RP can compare it against the issuer it started with; without it, the RP must bind state to the issuer server-side and look the issuer up from that record.

Alternatives and when to pick them

ApproachWhat it buysCost / when not to use
Static allowlist, one ClientRegistration per issuerIssuer pinned at config time; no runtime trust decisionN registrations to manage; adding a provider is a deploy
Dynamic client registration (RFC 7591)Providers self-registerYou now trust an unauthenticated registration endpoint; needs an initial access token and review
One RP instance per providerStrongest isolation: separate keys, caches, callback URLsN deployments; only worth it for high-assurance or regulatory splits
Single multi-issuer clientFewer moving partsOnly safe with RFC 9207 iss plus per-issuer key sets; easy to get wrong

The check, in order

Python
# Python 3.12 — illustrative, not a library binding
def handle_callback(txn_id, params):
    txn = txn_store.pop(txn_id)          # single-use, server-side
    if params.get("state") != txn.state:
        raise Reject("state mismatch")
    if "iss" in params and params["iss"] != txn.issuer:
        raise Reject("issuer mismatch")   # RFC 9207 mix-up guard
    if params.get("error"):
        raise Reject(params["error"])
    tokens = txn.issuer.token_endpoint(   # pinned, not from params
        code=params["code"],
        redirect_uri=txn.redirect_uri,
        code_verifier=txn.code_verifier,  # PKCE S256
        client_id=txn.client_id,
    )
    claims = verify_id_token(tokens["id_token"], txn.issuer.jwks, txn.issuer.issuer)
    if claims["nonce"] != txn.nonce:
        raise Reject("nonce mismatch")
    return claims

Trace it: state is checked first, so a replayed or swapped callback dies before any network call. iss is checked next, before the token endpoint is chosen. The token endpoint, redirect URI, client ID and JWKS all come from txn.issuer, so a response cannot redirect the exchange. nonce is checked last, against the ID token, which is what stops a token minted for a different login from being accepted.

Failure modes to name

  • Mix-up: code delivered to the wrong token endpoint. Detected by the iss mismatch above, or by a state lookup that misses.
  • Key confusion: a JWKS cache keyed by nothing, so provider B's key validates provider A's token. Key the cache by issuer URL and refresh on an unknown kid.
  • Subject collision: the same sub from two providers mapping to one account. Namespace external identities by (iss, sub).
  • aud/azp confusion: a token minted for another client of the same issuer. Check aud contains our client ID and azp equals it when present.
  • Callback swapping: a shared callback URL with no per-transaction binding. Distinct callbacks per provider add separation but are not a substitute for the state/iss checks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Implement step-up authentication for a sensitive operation.

Answer

What I'd say first (60–120s)

Assumptions: the user already has a session; the sensitive action runs server-side so I can gate it; the IdP supports OIDC with max_age and acr_values (SAML equivalent: ForceAuthn="true" plus RequestedAuthnContext).

Four steps. One, set the bar from the transaction's risk: how recent the authentication must be, and how strong. Two, send a fresh authorization request that asks for exactly that bar, max_age=300&acr_values=<required>, with a new state, nonce and request ID. Three, on return, validate auth_time and acr against the bar, not just the signature. Four, bind the result to this user, this session, and this one action, with a short expiry, and log the decision.

Step four is where implementations break. A step-up result that is just "this session is now strong" is a confused-deputy hole: any other endpoint can spend it.

Alternatives and when to pick them

OptionWhat it provesCostPick it when
OIDC max_age + acr_valuesFresh auth within N seconds, at a named assuranceFull redirect; user re-enters credentials unless the IdP session is already freshThe IdP is your assurance authority and you need a portable, auditable claim
prompt=login aloneUser is present now; no assurance levelRedirect, breaks SSO convenienceThe risk is freshness, not factor strength
WebAuthn re-assertion, userVerification: "required"Possession of the key plus user verificationNo redirect; needs an enrolled credentialYou control the client and want phishing-resistant step-up
Full re-loginA new sessionLoses session stateSession integrity itself is suspect

The deciding question is whether the risk is staleness or strength. Staleness → max_age. Strength → acr_values or WebAuthn UV. If you cannot trust the IdP to assert the assurance you need, don't ask it: do WebAuthn locally.

Failure modes and detection

  • Confused deputy. Step-up result replayed for a different action. Detect: the stored action_id doesn't match the request; alert on any step-up record used twice.
  • IdP ignores max_age. It returns an auth_time from an old session. Detect: log now - auth_time at validation; alert when it exceeds the requested max_age.
  • ACR downgrade. IdP returns a weaker acr than requested. Detect: reject anything outside the required set and count rejections per IdP.
  • Session fixation. Step-up bound to a session ID the attacker set. Detect: rotate the session ID at step-up.
  • Token replay. Detect: single-use nonce store, reject a second use.

Validation, traced

Python
# Python 3.12
REQUIRED_ACR = {"urn:mace:incommon:iap:silver"}  # deployment-defined

def accept_step_up(tok, sess, action_id, now):
    if tok["iss"] != ISSUER: return "reject: issuer"
    if tok["aud"] != CLIENT_ID: return "reject: audience"
    if tok["nonce"] != sess["step_up_nonce"]: return "reject: nonce"
    if now - tok["auth_time"] > MAX_AGE_S: return "reject: stale"
    if tok["acr"] not in REQUIRED_ACR: return "reject: acr"
    sess["step_up"] = {"sub": tok["sub"], "acr": tok["acr"],
                       "action_id": action_id, "expires_at": now + 120}
    return "ok"

Trace, MAX_AGE_S = 300. Session S holds step_up_nonce = "n1". The IdP returns a token with nonce="n1", auth_time = now-30, acr="urn:mace:incommon:iap:silver", sub="u1".

  1. accept_step_up(tok, S, "wire-42", now) → every check passes → S["step_up"] = {sub:"u1", acr:silver, action_id:"wire-42", expires_at: now+120} → "ok".
  2. 20s later, a request to execute "wire-99" reads S["step_up"]: action_id is "wire-42", not "wire-99" → reject. That is the confused-deputy block.
  3. 130s later, a request for "wire-42": now+130 > now+120 → reject: expired.

Log the decision (user, action, acr, auth_time, outcome) never the raw assertion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design local and federated logout behavior.

Answer

What I'd say in the first two minutes

Assume an OIDC OP, a handful of browser RPs, and that we control the OP and most RPs. Local logout and federated logout are two different operations with different guarantees, and I'd never let the second gate the first.

Local logout is unconditional. Delete the server-side session record, then clear cookies. Cookie clearing only works if Path, Domain, Secure and SameSite match the original Set-Cookie exactly: a cookie written with Domain=.example.com is not cleared by a Set-Cookie without Domain. Rotate the session ID at login, not logout. Make the endpoint idempotent: a second call returns the same 200 and does nothing.

Federated logout is best-effort fan-out. RP-initiated logout is a GET to the OP's end_session_endpoint (advertised in discovery) with id_token_hint, post_logout_redirect_uri, and state. post_logout_redirect_uri must exactly match a value registered for that client; the OP must not redirect otherwise. If id_token_hint is absent the OP should ask the user to confirm: that's the forced-logout protection, since otherwise anyone can log you out.

The OP then fans out to each RP that registered a logout URI:

Front-Channel Logout 1.0Back-Channel Logout 1.0
MechanismOP renders hidden iframes to frontchannel_logout_uriOP POSTs a logout token to backchannel_logout_uri
Session targetingiss and sid query params when frontchannel_logout_session_required is truesid and/or sub claims in the token
Confirmationnone: fire and forgetRP returns 200/204; OP should retry on failure
Breaks whenthird-party cookies blocked, CSP frame-ancestors, tab closed earlyRP unreachable server-side, or RP doesn't validate the token
Clears browser cookieyes, if the iframe can runno: only the server session dies

Worked trace of a back-channel logout token, decoded:

{ "iss": "https://op.example.com",
  "aud": "client-7",
  "iat": 1730000000,
  "jti": "b1c2",
  "sub": "user-42",
  "sid": "sess-9f",
  "events": {"http://schemas.openid.net/event/backchannel-logout": {}} }

The RP checks: signature against the OP's JWKS, iss equals the OP, aud equals its own client_id, events contains that key, and no nonce is present (a logout token carrying a nonce must be rejected). Then it matches sid to a live session and deletes it. If sid is absent it must kill every session for sub.

Failure modes I'd name: IdP down. Local logout still completes and the UI says "signed out here; other apps may still be signed in." Front-channel iframe blocked by frame-ancestors. Silent no-op, no error surfaces anywhere, which is why I don't count it as a guarantee. Back-channel 500: OP retries; if the RP stays down the session lives until its token expires. Missing sid: you can only do a global logout for the user, not a per-session one.

When I wouldn't attempt federated logout: RPs that advertise neither logout URI, public clients the OP can't reach server-side, or sessions with 5-minute access tokens where expiry is cheaper than a fan-out. Then say so in the UI rather than implying a global logout happened.

What would change the decision: if every RP is first-party and reachable, back-channel alone is enough. If the requirement is that the browser cookie is gone, you need front-channel and you accept its unreliability. If the OP can't reach RPs, front-channel is all you have.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Implement secure SAML Web Browser SSO validation.

Answer

Assumptions: SP-initiated Web Browser SSO, the IdP signs the Assertion (some sign only the Response), you hold the IdP signing certificate from metadata, and your ACS endpoint is the only place assertions are consumed.

Core answer (first 90 seconds). Parse the POSTed SAMLResponse with a hardened XML parser (DTDs and external entities off, no network, a size cap and a depth cap) because the first bug class here is XXE and billion-laughs, not signature logic. Then verify the XML signature over the exact element you are about to read, and read that same element. Everything after is context validation: Status is Success; Issuer matches the IdP entityID; Destination on the Response and Recipient on the SubjectConfirmation both equal your ACS URL; Audience equals your SP entityID; NotBefore/NotOnOrAfter bracket now within a bounded skew; SubjectConfirmation Method is bearer; InResponseTo equals the request ID you stored and is consumed once. Only then map identity: key on (Issuer, NameID), never NameID alone.

Why each check exists. The signature is the only thing that makes the rest trustworthy, so it is checked first and bound to the consumed node. XML Signature Wrapping punishes any gap between "what I verified" and "what I read":

  1. Attacker captures a valid Response containing signed Assertion A (claims alice@corp).
  2. Re-wraps it: A is moved inside <Extensions> or a second <Response>, and a forged Assertion F (claims admin@corp) is placed where the SP's XPath //Assertion resolves first.
  3. Naive SP: XPath returns F, verifies the signature over A (still present, still valid), passes, then reads F → privilege escalation.
  4. Correct SP: verification returns the node the signature's Reference URI points at (A); consume A. F is never read.
Python
from lxml import etree
from signxml import XMLVerifier

parser = etree.XMLParser(resolve_entities=False, load_dtd=False,
                         no_network=True, huge_tree=False)
root = etree.fromstring(saml_response, parser)

# verify returns the element the signature actually covers
verified = XMLVerifier().verify(root, x509_cert=idp_cert,
                                expect_references=1).signed_xml
assert verified.tag == "{urn:oasis:names:tc:SAML:2.0:assertion}Assertion"
# consume `verified`, never a fresh XPath lookup

Trade-offs. Library vs hand-rolled: python3-saml, ruby-saml, Spring Security SAML and Shibboleth SP have all shipped XSW fixes; hand-rolling is where you reintroduce them. Use a library unless you have a specific reason not to. Metadata auto-refresh vs pinned keys: auto-refresh survives IdP key rollover without a deploy but trusts the metadata endpoint. Sign the metadata and pin the metadata signing cert. Pinning the assertion cert is simpler but breaks silently on rollover. Hourly refresh is a common interval; shorten it if the IdP rotates often.

Failure modes and detection. Clock skew: tolerance is typically 60–90 s (some stacks allow 5 min); too tight rejects valid logins under NTP drift, too loose widens the replay window. Log NotBefore/NotOnOrAfter against server time on every rejection. Replay: InResponseTo must be single-use and stored server-side; a reused ID means a stolen assertion. Count duplicate assertion IDs. Audience mismatch: multi-tenant SPs that skip Audience accept assertions minted for another SP on the same IdP.

CheckDefends againstSymptom if skipped
Signature over the consumed nodeXSW, forged claimsattacker-chosen identity accepted
DTD/entities offXXE, billion laughsfile read / DoS
Audience = SP entityIDcross-SP assertion reusetenant A's assertion works on tenant B
Recipient/Destination = ACSassertion redirected elsewheretoken replay at a different SP
InResponseTo single-usereplaystolen assertion reused
Skew 60–90 sclock driftvalid logins rejected, or widened replay window

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design SAML replay and assertion-injection protection.

Answer

Assumptions: SP-initiated SAML 2.0 Web Browser SSO, HTTP-POST binding to the ACS, IdP signs the assertion (or the response), SP holds the IdP signing cert out of band. If any of those is false the answer changes: see the end.

The 90-second answer

Replay and assertion injection are one bug seen from two sides: the SP accepts an assertion that isn't tied to this browser session, or accepts the same one twice. Four controls, all required:

  1. Correlation. The SP generates the AuthnRequest ID (SAML 2.0 Core §3.4.1), stores it in the session, and requires InResponseTo to equal it. This is what kills unsolicited and injected responses.
  2. Context binding. Audience = SP entityID; SubjectConfirmationData/@Recipient = the exact ACS URL.
  3. Time. Conditions/@NotBefore and @NotOnOrAfter (Core §2.5.1.1) plus SubjectConfirmationData/@NotOnOrAfter (Core §2.4.1.2), evaluated with ±60–90 s of clock skew. IdPs commonly issue 5-minute assertions.
  4. Uniqueness. The assertion ID is consumed exactly once, atomically, with a TTL equal to the acceptance window.

Underneath all four: verify the XML signature over the element you actually consume, not over some other node in the document.

Validation order and the values to enforce

CheckEnforceBlocks
InResponseToequals stored AuthnRequest ID; that ID is single-useunsolicited / injected response
Recipientexact ACS URLassertion forwarded to another endpoint
Audienceexact SP entityIDassertion minted for a different SP
NotBefore / NotOnOrAfternow ∈ [NotBefore − 90 s, NotOnOrAfter + 90 s]stale assertions, clock skew
SubjectConfirmation/@Methodbearer, with SubjectConfirmationData presentholder-of-key confusion
Signatureover the consumed element, IdP cert, exclusive c14ntampering, XML Signature Wrapping
Assertion IDfirst use only, TTL = windowreplay

Atomic single-use consume

Python
# Python 3.11, redis-py 5.x
def consume_assertion(redis, assertion_id, not_on_or_after, skew_s=90):
    ttl = int((not_on_or_after - datetime.now(timezone.utc)).total_seconds()) + skew_s
    if ttl <= 0:
        return False
    # SET NX EX: True for the first caller, None for every later one
    return bool(redis.set(f"saml:assertion:{assertion_id}", "1", nx=True, ex=ttl))

Trace, two ACS POSTs carrying the same assertion, NotOnOrAfter 240 s out: first call computes ttl = 330, SET NX returns True → proceed. Second call, same key, SET NX returns None → False → 403. A DB equivalent is INSERT ... ON CONFLICT DO NOTHING and reject when rowcount == 0.

Injection: the wrapping trace

Response contains Assertion A (attacker-forged, unsigned) and Assertion B (genuine, signed, for another user). Naive code does getElementsByTagName('Assertion')[0] → picks A, then verifies the signature over B → passes. Fix: resolve the signed element by its ID reference and consume that node; reject if the document holds more than one Assertion or if the signed ID isn't the consumed one.

Failure modes

  • Skew too tight → valid logins rejected at the boundary; too loose → the replay window grows past the assertion lifetime. 90 s is the usual compromise.
  • Replay store not shared across ACS nodes (multi-region, no sticky routing) → the same assertion is accepted once per node. Needs shared Redis/DB or sticky sessions.
  • Proxy/LB retry re-POSTs the ACS request → the second attempt hits the same assertion ID and is rejected, so one assertion yields one local session.
  • CSRF on the ACS → attacker forces the victim's browser to POST the attacker's assertion, fixing the session. Bind RelayState to the session cookie and set SameSite=Lax on it.

What changes the decision

If IdP-initiated SSO is a hard requirement, InResponseTo is unavailable; you fall back to a pre-registered RelayState bound to the session, a tighter audience check, and a shorter window, and you accept a larger injection surface. If the IdP can't sign the assertion, none of this holds and you need a different transport.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Evaluate whether to support IdP-initiated SAML SSO.

Answer

Verdict: Default to SP-initiated. Support IdP-initiated only when a named requirement forces it, usually app-launcher tiles in Okta or Entra ID My Apps, and only for an explicit allowlist of tenants and IdPs. If you can't enforce the controls below, the answer is no.

Assumptions: SAML 2.0 Web Browser SSO Profile; you own the SP and its ACS endpoint; IdP metadata is exchanged out of band and pinned; you have a server-side session store.

Why SP-initiated binds the transaction. The SP mints an AuthnRequest with a unique ID and stores it against the browser session. The IdP echoes that ID in InResponseTo. On the way back the SP checks three things that exist only because the SP started the flow: InResponseTo matches a request it issued and hasn't consumed, the browser presents the same session cookie that started the flow, and the RelayState is one the SP generated. An attacker holding a captured signed assertion can satisfy none of them: no pending request ID, no victim pre-login cookie.

Why IdP-initiated doesn't. There is no AuthnRequest, so InResponseTo is absent by definition and there is nothing to match. The POST arrives cold at the ACS URL, so there is no session to correlate. RelayState comes from the IdP, and reflecting it into a redirect hands the attacker an open redirect. What's left is the signature, and the signature only proves that some IdP in your metadata signed something.

How that gets exploited. Take a federation where the SP trusts two IdPs, or one IdP fronts several tenants. An attacker who can obtain a signed assertion for the victim: from a rogue SP registered with the same IdP, from a compromised IdP, or from a leaked assertion: POSTs it to your ACS. With no InResponseTo and no session binding, you mint a session for the victim. Cross-tenant is the same move: tenant A's assertion replayed at tenant B's ACS when Audience and Recipient aren't checked. The other family is XML Signature Wrapping, where the signature covers a benign element while your parser consumes a swapped one; Somorovsky et al. (USENIX Security '12) broke 11 of 14 SAML frameworks this way.

If you must support it.

ControlConcrete setting
Trust scopeAllowlist of tenant+IdP pairs; separate ACS path per tenant
AudienceAudience must equal your SP entityID exactly
RecipientSubjectConfirmationData/@Recipient must equal the ACS URL byte-for-byte, no wildcards
TimeCap NotOnOrAfter at ~5 min after IssueInstant; accept at most ~2 min clock skew
ReplayCache Assertion/@ID in Redis with TTL equal to the validity window; reject duplicates
SignatureVerify against the pinned IdP cert; reject if Response and Assertion are both signed and disagree; resolve XSW by consuming only the signed element
RelayStateThe Web Browser SSO profile caps it at 80 bytes; map it to a server-side allowlist, never redirect to it
Sensitive actionsRe-authenticate or step up MFA for account linking, password change, admin

What would change the answer. If the IdP is the only entry point, no SP-side login page at all, you have to accept it, and the table above is the whole defence. If you can require a pre-existing SP session before honouring an unsolicited response, you recover most of the binding. If the federation is one IdP, one tenant, pinned metadata, and assertions are short-lived and single-use, the residual risk is small enough to accept in writing.

Failure modes to test. Replay a captured assertion twice: the second must fail. POST tenant A's assertion to tenant B's ACS: must fail on audience. Send an XSW payload: must fail. Send an expired assertion: must fail. Log every rejection with the assertion ID and reason, and alert on a spike; that spike is what an injection attempt looks like in production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design federated identity mapping and account linking.

Answer

Core answer. Key every external identity on the pair (issuer, subject): for OIDC the iss and sub claims from the ID token, for SAML the IdP's entityID plus a persistent NameID, and store that pair in a link table that points at your local user row. Email, username and display name are attributes you may use to suggest a match, never to establish one. Auto-linking on a matching email address is the account-takeover path: an attacker registers at a permissive IdP with victim@company.com and inherits the account.

Assumptions. You are the OIDC RP / SAML SP, you own the local user table, and your IdPs are OIDC or SAML 2.0. If any IdP only ever sends an email address and no stable subject, you are in a different regime: see the close.

Which claims are keyable.

claimsourcekeyable?why
subOIDC ID token, requiredyes, paired with issOIDC Core 1.0 §2 defines it as locally unique and never reassigned within the issuer
issOIDC ID token, requiredyesscopes sub to one issuer; without it two IdPs can mint the same sub
audOIDC ID tokenno: validate onlystops a token minted for a different client being replayed at yours (OIDC Core 1.0 §3.1.3.7)
email + email_verifiedOIDCnoemail_verified records that the IdP checked the address once, not that it stays yours; Workspace and Entra both recycle addresses
NameID, persistent formatSAML Subjectyes, paired with IdP entityIDstable across logins
NameID, transient formatSAML Subjectnonew value every login: keying on it mints a fresh account per sign-in
eduPersonPrincipalName, employeeIdSAML AttributeStatementnoreassignable by the IdP at any time

The SAML NameID Format URIs are urn:oasis:names:tc:SAML:2.0:nameid-format:persistent and :transient (SAML Core 2.0 §8.3); reject a transient NameID as a key at the SP.

Schema.

SQL
CREATE TABLE identity_link (
  provider_id      text        NOT NULL,  -- OIDC iss, or SAML IdP entityID
  external_subject text        NOT NULL,  -- sub, or persistent NameID
  user_id          uuid        NOT NULL REFERENCES app_user(id),
  linked_at        timestamptz NOT NULL DEFAULT now(),
  link_method      text        NOT NULL,  -- 'jit' | 'reauth' | 'admin'
  PRIMARY KEY (provider_id, external_subject)
);

The primary key is the whole defence: it makes a duplicate link impossible at the storage layer rather than in application code. Whether you also add UNIQUE (user_id, provider_id) is a policy call: one identity per provider per user is the common default, but B2B tenants often need several.

Linking flows.

Just-in-time. No link exists and the trust policy allows provisioning. Restrict this to a first-party IdP or a domain you control, checked via the hd claim (Google) or a verified-domain claim, and create the user and the link in one transaction.

Explicit link. The user is already signed in locally and clicks "connect this identity". Require reauthentication of the current session, then run the OIDC flow with prompt=login, or SAML with ForceAuthn="true", so the IdP re-authenticates instead of silently reusing an existing browser session. Bind the two halves in one request: the state/nonce you issued is tied to the current session, so the new identity can only attach to the account that started the flow.

Never. Auto-link because email matches. That is the whole attack.

Unlinking. Count the user's authentication methods: password hash, each identity_link, passkeys, unused recovery codes. If the count is 1, refuse the unlink and require a password be set first; otherwise a user who linked one IdP and forgot the password locks themselves out permanently. Notify the owner on a channel that does not depend on the identity being removed, and write an audit row for every link and unlink with actor, method and timestamp.

Failure modes. An IdP that recycles sub after account deletion, despite the spec, silently hands a new person the old account. Detect it by storing a second stable attribute at link time and comparing on each login; a mismatch is an alert, not a re-link. A transient NameID shows up as link-table growth per user. Two IdPs claiming the same email for different people shows up as a collision: route those to an admin review queue keyed on the normalized address rather than resolving them automatically. SCIM 2.0 deprovisioning (active: false, RFC 7643 §4.1.1) must disable the user and revoke sessions, but keep the link row, so a rehire re-attaches instead of creating a second account.

What would change the decision. If the IdP is first-party and you own the subject namespace, drop the link table and make the subject the primary key. If you are B2B with per-tenant IdPs, the tenant belongs in the key alongside the issuer. If an IdP genuinely offers no stable subject, treat every login as unverified and require an out-of-band confirmation before the identity attaches to an existing account.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Handle email reuse, rename, and account collision in federation.

Answer

The only stable identifier in federation is the pair (issuer, subject). Email is a mutable contact attribute. So bind accounts to (iss, sub), store email separately, and never use email as the primary key.

Assume OIDC or SAML federation with JIT provisioning. The IdP is authoritative for identity. OIDC Core 1.0 says sub is locally unique and never reassigned. email is just a claim; it can change and be reused. email_verified tells you the IdP verified it at some point, not that it's stable.

When a user changes email at the IdP, the sub stays the same. Update the email attribute, keep the account binding. When a new user presents an email that already exists in your system but with a different sub, that's a collision. Auto-linking by email would let the new user take over the old account if the email was reassigned. So require proof: the existing account confirms the link, or an admin resolves it. For low-risk accounts, you might allow auto-linking if the IdP guarantees no email reuse and email_verified is true, but that's rare.

Concrete failure: User A deletes their IdP account. The IdP allows email reuse. User B signs up with the same email, gets a new sub. If you auto-link, B gets A's data. Detection: monitor for email collisions where sub differs; alert on auto-link attempts. Cost: account takeover, data breach. Rename failure: User changes email at IdP. If you treat email as key, you create a new account or lock them out. Detection: login failures after email change. Cost: support tickets. Tenant migration: Issuer changes. If you rely on iss, you need a migration path. Detection: login failures with old iss. Cost: downtime.

Trade-offs: Auto-linking by email is convenient but unsafe. Acceptable only when the email is verified and the IdP guarantees no reuse, and even then only for low-risk accounts. Domain-based auto-join: use domain as a hint, but require email verification and admin approval for privileged access. What would change the decision: if the IdP provides a globally unique, immutable identifier that is guaranteed never reused, then email could be a secondary key. But sub is the only stable key.

Here's a table of identity attributes:

AttributeSourceStabilityUniquenessUse as key?
iss + subIdPImmutable per specLocally uniqueYes
emailIdP claimMutableNot guaranteedNo
email_verifiedIdP claimBooleanN/AOnly for verification

Trace of a collision:

  1. User A (iss=idp.example.com, sub=123) has email alice@example.com.
  2. User A deletes account at IdP. IdP allows email reuse.
  3. User B signs up at same IdP, gets sub=456, email alice@example.com.
  4. User B logs into our app. We see iss=idp.example.com, sub=456, email=alice@example.com.
  5. We look up by (iss, sub) -> no account. We look up by email -> find User A's account.
  6. If we auto-link, User B gains access to User A's data. Instead, we block and require proof.

This keeps identity stable while allowing email changes. The key is to separate identity from contact attributes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Map federated groups and claims to local authorization.

Answer

Assume an OIDC or SAML IdP, a multi-tenant SaaS API, and local RBAC roles. The short answer: treat the IdP as the source of group membership, not authorization. Translate immutable group IDs from an allowlisted issuer into local roles through a versioned mapping table, deny by default, and re-evaluate on token validation plus SCIM lifecycle events.

Mechanism. On each request, validate the token signature, then iss, aud, and exp. Extract the group claim. Entra ID emits groups as object IDs (GUIDs) and roles for app roles; Okta can emit groups as names or IDs depending on configuration; Keycloak emits groups as paths like /engineering/platform; SAML commonly uses memberOf. Look up each value in a mapping table keyed by (issuer, claim, value, tenant, env). Unmapped values are dropped. If no mapped roles remain, deny. The table is the reviewable artifact:

issuerclaimvaluetenantenvlocal role
https://login.microsoftonline.com/72f988bf-.../v2.0groups8f3a...acmeprodreader
https://acme.okta.comgroups00g1a2b3c4acmeprodincident-commander

A Rego policy that enforces this:

REGO
package authz

default allow = false

allow {
  input.token.iss == "https://login.microsoftonline.com/72f988bf-.../v2.0"
  input.token.aud == "api://acme-prod"
  input.tenant == "acme"
  input.env == "prod"
  some g in input.token.groups
  role := group_role[g]
  role == "reader"
}

group_role := {
  "8f3a...": "reader",
  "b2c1...": "incident-commander",
}

Trace: token has groups = ["8f3a...", "deadbeef"]. some g finds 8f3a..., group_role["8f3a..."] is reader, so allow is true. deadbeef is ignored. If groups = ["deadbeef"], no iteration satisfies group_role[g], so allow stays false. Deny-by-default matters because a new or mistyped IdP group must not silently grant access.

Failure modes.

  1. Group overage. Entra ID caps the groups claim at 200 for JWT and 150 for SAML, then emits _claim_names and _claim_sources instead. If your PDP ignores the overage, the user gets zero groups and deny-by-default locks them out. Detect by alerting when _claim_names is present; fall back to Microsoft Graph GET /users/{id}/transitiveMemberOf with GroupMember.Read.All. Cost: extra API call and Graph throttling.

  2. Stale membership. Entra ID’s default access token lifetime is 1 hour. Remove a user from a group at T; their token still carries the old group until T+1h. Detect by consuming SCIM PATCH /Groups/{id} events and revoking sessions; measure revocation lag and alert if it exceeds 5 minutes. Cost: up to an hour of stale privileged access if you only rely on token expiry.

  3. Name-based mapping. Mapping on displayName breaks when a group is renamed or its name is reused. Use immutable IDs (Entra object ID, Okta group ID). Detect by monitoring mapping misses and unexpected role grants; alert on any grant not backed by a current ID.

  4. Conflict. A user in two groups mapping to reader and incident-commander needs a precedence rule: deny wins, or union with a tenant cap. Detect by logging the rule IDs that fired and alerting on multi-role grants.

Trade-offs. Pass-through with scoping trusts IdP groups directly as roles. It is simpler, but couples API roles to IdP naming, breaks on rename, and leaks across tenants if group names collide. Use it for single-tenant internal tools. JIT group provisioning creates local groups from the IdP on first login. It reduces mapping maintenance but drifts; reconcile nightly against SCIM. A central PDP (OPA sidecar, Cedar) gives consistent policy and audit; a sidecar adds roughly 1–5 ms per decision, a remote PDP 20–50 ms. Embedded libraries are faster but scatter policy across services. Pick by blast radius, tenant count, and audit needs. The mapping table is what you review; the token is just input.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design joiner-mover-leaver lifecycle around federated SSO.

Answer

What I'd say first

Assume the IdP (Okta, Entra ID) is the authentication authority, the app is the relying party, and provisioning is SCIM 2.0 pushed from the IdP. The framing that matters: SSO and lifecycle are different planes. SSO decides whether the next authentication succeeds. It does nothing to the session, refresh token, or API key that already exists. So the design has three planes (authentication, provisioning, and local session/token state) and the leaver path has to touch all three.

Why disablement alone isn't enough

When you disable someone in the IdP, the next OIDC or SAML login fails. Everything already issued keeps working. Example lifetimes for a typical config: check your own IdP, these are illustrative:

artefactexample lifetimekilled by IdP disable?
IdP session cookie8hno, until the IdP session ends
RP session cookie8hno
OIDC refresh token90dno, unless you call the revocation endpoint
Access token1hno
API key / PATuntil rotatedno

So the exposure window after a disable is the longest-lived artefact you didn't revoke. That's why revocation is the higher-leverage control than the disable itself.

Trade-offs

JIT provisioning vs SCIM push. JIT creates the account on first login (cheap, no connector) but it cannot deprovision. A leaver who never logs in again is never touched, and attributes drift. SCIM push gives create/update/deactivate but needs a connector and a reconciliation safety net. Use JIT for low-risk self-serve apps; SCIM for anything touching data.

Push vs reconcile. Push is fast (seconds) but lossy: webhook delivery fails, the app is down during the event, ordering breaks. Reconcile is a full diff on a schedule and catches drift, but it's slow and costs a full list call. You need both: push for latency, reconcile as the net.

Group-based vs per-user mapping. Group mapping scales and matches how IdP admins work, but nested groups and group renames are a common drift source.

Failure modes

  • Missed deprovision: the app was down during the SCIM call. Detect: reconcile diff count > 0, alert on it. Blast radius: the leaver keeps access until the next reconcile window.
  • Orphaned resources: user deactivated, but their service accounts, buckets, and CI tokens remain. Detect: periodic access review with owner attestation.
  • Rehire: same email, new or returning person. Key on the immutable IdP subject ID, not email, or you resurrect old entitlements.
  • Token not revoked: refresh token still valid. Detect: attempt a refresh after disable in a test.

Trace of a leaver event

  1. HR marks terminated in the HRIS.
  2. IdP deactivates the account, emits SCIM PATCH active=false.
  3. App receives it, sets the local user inactive, kills sessions, revokes refresh tokens.
  4. If step 3 fails, reconcile at T+1h diffs IdP-active vs app-active and re-issues the deactivate.

Arithmetic. If push fails and reconcile runs hourly, worst-case access exposure is 60 minutes. If a 90-day refresh token also survives, exposure is 90 days. Same event, two orders of magnitude apart, which is the whole argument for treating revocation as the primary control and reconcile as the backstop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Implement reliable SCIM deactivation and reconciliation.

Answer

Core answer. SCIM 2.0 (RFC 7644) is a provisioning protocol, not an authentication one: deactivation is active=false on the User resource, not DELETE /Users/{id}. Assume the IdP is the source of truth, the target app holds its own sessions, tokens and caches, and the SLA is "no effective access after N minutes". The answer is three phases: idempotent deactivation via PATCH, fan-out revocation of every access path the directory row does not cover, and periodic reconciliation that repairs missed or reordered events.

Deactivation. PATCH with a replace on active is idempotent in effect: replaying it converges on the same state, unlike PUT, which requires the full resource and lets a stale client resurrect fields it did not know about. Guard concurrent writers with ETag/If-Match:

PATCH /scim/v2/Users/2819c223-7f76-453a-919d-413861904646
Content-Type: application/scim+json
If-Match: W/"e180ee84f0671b1"
{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
 "Operations":[{"op":"replace","path":"active","value":false}]}

A second deactivation with the same ETag gets 412 Precondition Failed; with a fresh ETag it succeeds and is a no-op. That is the mechanism that makes retries safe.

Revocation fan-out. active=false closes the directory row. It does not close a refresh token issued 30 seconds earlier. Enumerate every path and give each a target:

pathmechanismtarget (hypothetical)
SCIM activePATCH replacenext request
OIDC access tokenshort TTL≤15 min
OIDC refresh tokenRFC 7009 revocation endpoint≤60 s
Web sessionsession-store delete + OIDC back-channel logout≤60 s
Cached group/roleinvalidate on group PATCH≤5 min

Reconciliation. Events can be reordered: a queued active=true from before the deactivation can land after it. A periodic diff catches that. Pull the target's active set and compare to the source:

GET /scim/v2/Users?filter=active eq true
  &attributes=userName,active,meta.lastModified
  &count=100&startIndex=1

Page by startIndex += count. Any user active in the target but not the source is drift; re-issue the PATCH. For incremental runs, filter=meta.lastModified gt "<last run>" narrows the pull where the target supports it. Alert if drift count is non-zero for two consecutive cycles: one cycle is usually in-flight events.

Trade-off: preserve vs cascade. The deciding criteria are data ownership and legal hold, not a blanket rule. If the user owns shared documents, transfer ownership first, then deactivate; if the data is under a retention policy, keep it and deactivate. The choice flips for a contractor with no owned content during a security incident: cascade delete is correct, and the audit record is the only thing retained.

Failure modes. Partial revocation, directory inactive but refresh still succeeds, is detected by joining token-introspection logs against the deactivation timestamp. Reconciliation drift is detected by the count mismatch above. A target that ignores If-Match falls back to last-writer-wins on active only, logged as a degraded path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design privacy-preserving federation attributes.

Answer

What I'd say in the first two minutes. The question is underspecified, so I'd pin it down before designing: an IdP (Okta, Entra, Keycloak) issuing identity to a set of relying parties that are not equally trusted. An internal wiki, a payroll SaaS, a third-party analytics tool. Assumptions I'd state out loud: the IdP is authoritative for identity, the HR system is authoritative for employment and entitlements, and the RPs are independent parties that can be breached or collude. Given that, the design rule is three-part: release the minimum claim set per RP, make the subject identifier non-correlatable across RPs, and keep volatile entitlements out of long-lived tokens.

Mechanism. The correlatable part is almost always the subject. In OIDC, set subject_types_supported: ["pairwise"] with a sector_identifier_uri; the IdP then derives a per-RP sub so the same human gets a different opaque value at each RP. The spec doesn't mandate the derivation, but a common construction is sub = base64url(SHA-256(sector_identifier || local_user_id || per-IdP-salt)): stable for a given (RP, user) pair, useless for joining across RPs. The SAML equivalent is <NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">, which is generated per session and carries no persistent identifier at all; use persistent NameID only when the RP genuinely needs to remember the user between sessions.

Claim minimization is per-RP configuration, not a global default: OIDC's claims parameter (OIDC Core 1.0 §5.5) and SAML per-SP attribute statements both let you scope exactly what leaves the IdP. Entitlements are the volatile part: a role list that changes hourly does not belong in an ID token with a 24-hour life. Push them via SCIM 2.0 (RFC 7643/7644) or expose an entitlement endpoint the RP calls with its own credentials.

attributesource of truthchannellifetime
sub (pairwise)IdPID tokenstable per (RP, user)
emailIdPID token, only RPs needing contactstable
department, managerHRID token24 h
roles / entitlementsHR + app DBSCIM push or entitlement API5–15 min
clearance levelsecurity systemintrospection per requestper request

Failure modes and how you'd catch them. (1) A stable email used as the subject lets two RPs join on it: detect by scanning per-RP token logs for the same identifier value appearing at two RPs. (2) An over-broad ID token turns any single RP breach into a full-directory leak: detect with a per-RP claim inventory diff, alerting when a new claim appears. (3) A revoked role still inside a 24-hour token means an offboarded user keeps access: measure the revocation-to-expiry gap and target it below the token TTL. (4) Collusion on quasi-identifiers re-identifies people even when each field looks harmless: a department of 6, split 3/3 by office, with hire year making one person unique, gives k=1. Detect by running a k-anonymity check over the union of attributes released to any set of RPs, not per RP.

Trade-offs. Pairwise sub breaks cross-RP account linking and makes support harder: you can't look a user up by subject. Transient NameID breaks session continuity. Inside a single trust domain (one company's own apps) a stable subject is simpler and fine; the cost only pays off when RPs are genuinely independent. When you can't avoid releasing a quasi-identifier, bucket it (hire year, not date) rather than dropping the feature.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design federation observability and audit logging.

Answer

Clarify scope first: OIDC/SAML federation service, multi-tenant, ~50k auth attempts/min at peak, SCIM provisioning. Two streams, not one. Security audit is one immutable event per auth attempt and per provisioning action, 100% sampled, synchronous to a local WAL then async shipped. Debug telemetry is sampled (1% on success, 100% on failure) async only, 7-day retention. The split is the main trade-off: full-fidelity logging of every validation step gives 72M events/day at ~1KB each = 72GB/day and adds write-path latency to every login; sampling audit events loses the one question auditors ask, "did this user log in at 14:03?" So audit stays complete and small, debug stays cheap and lossy.

Fields that matter, and why:

FieldWhy it existsRetentionExample
timestampCorrelate across IdP/SP; NTP-synced, alert if skew >500ms30d hot, 1y cold2025-03-11T14:03:22.417Z
rp/client_idWhich app requested authsameacme-web
expected_iss / observed_issDetect mix-up attack where RP sends token to wrong issuersamehttps://idp.example.com vs https://evil.example
subject_hashHMAC-SHA256 with per-tenant salt, rotate quarterly; correlate without storing PIIsamea3f9...
correlation_idW3C traceparent propagated across IdP/SPsame00-4bf9...-01
flowauth code, refresh, token exchange, SAML POSTsameauthorization_code
validation_stagesignature, iss, aud, exp, nonce, acr: tells you where it failedsamenonce
outcome/reasonEnum, not raw error stringsameinvalid_nonce
assuranceacr/amr valuessameacr=urn:mace:incommon:iap:silver
policy/key_versionkid of signing key usedsamekid=2025-03-rsa
provisioning_actionSCIM create/update/deletesameDELETE /Users/123
actorAdmin who triggered provisioningsameadmin@example.com
latency_msp50/p99 per stage7dsig=2ms, iss=1ms

Never log raw codes, assertions, tokens, verifiers, client secrets, or session cookies. Hash subject with per-tenant salt. Redact URLs to scheme+host+path, drop query strings.

Pipeline: audit events go to Kafka topic federation.audit (7-day retention), consumer writes to ClickHouse for 30-day hot queries, then S3 Parquet for 1-year cold. Debug goes to Loki, 7-day retention. Access to audit requires a separate role plus MFA. Integrity via append-only storage and a per-tenant hash chain. Deletion is crypto-shredding: drop the tenant's HMAC salt and encryption key.

Failure modes and detection:

  • Replay: same jti seen twice within token lifetime. Detect with Redis SETNX keyed on jti, TTL = token exp. Alert if >5/min per issuer.
  • Issuer mismatch: expected_iss != observed_iss. Alert immediately, page on-call.
  • Linking: same subject_hash across >3 RPs without a consent record. Detect with a nightly graph query; alert on new edges.
  • Deprovision failure: SCIM DELETE returns 4xx/5xx. Retry 3x exponential backoff, alert after 3 failures.

Operational cost: logging adds ~3% CPU. 72GB/day raw; ClickHouse compresses ~10:1, so 30 days hot is ~216GB. S3 at $0.023/GB is ~$1.66/day cold. Write path: async adds <1ms p99; synchronous WAL adds 2–5ms p99. That is the budget you defend when someone asks to log every claim.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Build an adversarial federation test matrix.

Answer

Opening. I'd scope this to the SP side of OIDC and SAML, since that's where the validation code lives, and assume we control a signing key so we can mint malformed assertions: a real IdP won't produce them. The matrix has five layers, and every row has the same shape: mutate exactly one field from a known-good baseline, send it, assert the denial reason and the invariant that no local session, token, or privilege was created. One-variable mutation is the point; change two fields and you can't tell which control fired.

The matrix.

LayerRow (mutation)ExpectedInvariant asserted
Signaturealg=HS256 signed with the RSA public key as HMAC secretsignature failureno session
unknown kid, then rotated keyreject until JWKS refreshno session
Claimswrong iss/aud/azp; exp past, nbf futurerejectno session
nonce/state/InResponseTo mismatchrejectno code exchange
Replaysame jti/assertion ID twicesecond rejectedno second session
FlowPKCE missing, plain, or downgradedrejectno token issued
redirect_uri prefix, @, trailing-slash variantsexact match onlyno redirect
mix-up: code from IdP B redeemed at Areject on iss mismatchno session
Provisioninggroup removed, SCIM reorder/retry, disableaccess revokedno stale privilege
Robustness1 MB SAMLResponse, XXE entity, 10 min skewclean 4xxno 500, no OOM

Worked trace: alg confusion. Baseline: a valid RS256 ID token. The attacker decodes the header, sets alg: HS256, and HMACs the payload using the IdP's public key bytes as the secret. A correct verifier pins the algorithm to the registered one and fails at the signature check. A vulnerable one treats the public key as a shared secret and accepts. Assert: 401, the log names signature verification, and the session store has no entry for that sub.

Priorities and deciding criteria. Rank by whether a failure is silent. Signature, alg, issuer, audience, nonce and replay come first because a miss is account takeover with no error anywhere. PKCE, redirect and mix-up next: a miss is code theft. Key rotation and provisioning after that, then the DoS rows. The criterion is blast radius times detectability, not row count.

Trade-offs. The full cross-product is thousands of rows and nobody runs it. Run one-variable mutations plus a handful of pairwise combos, expired and wrong audience, to catch short-circuit ordering, where the first failing check masks the second. The build cost is a mock IdP with your own key; the alternative, a vendor test tenant, only exercises happy paths and rotation. Skew is the one place you must pick a number: a 60 s allowance (Nimbus's default claims verifier) means the replay cache must outlive the token by that much. A 5-minute access token needs a 6-minute jti cache, or a replayed token slips through in the last minute.

Failure modes. The common one is a row that passes for the wrong reason: the token is rejected because the signature check ran first, not because audience was validated. Fix by making every other field valid. Second, asserting only "rejected", if the log doesn't name the control, a regression that swaps one check for another is invisible. Third, partial session: the SP writes the session before validating the ID token, so a rejected login still leaves a cookie.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Respond to an IdP signing-key or federation metadata compromise.

Answer

Assumptions. I'm on the RP/SP side: I run the applications that consume the IdP's SAML assertions or OIDC ID tokens. The IdP is external (a partner or a SaaS IdP). I have admin on my RP config and my own audit logs, but not on the IdP. If the IdP itself is compromised, nothing it publishes is trustworthy until I re-establish trust out-of-band.

The core answer. A signing-key compromise means the attacker can mint assertions or ID tokens that pass signature validation for any subject, any audience, any role. Signature validation is the only thing separating "the IdP says this is alice@corp" from "anyone says this is alice@corp." So the moment the key is suspect, every token signed by it is untrusted: including ones already issued. The first move is to stop trusting the key, not to wait for token expiry.

In order:

  1. Preserve evidence before changing anything. Snapshot the metadata document, the JWKS, cert fingerprints, the RP trust config, and recent assertion/audit logs. openssl x509 -in idp.crt -noout -fingerprint -sha256 gives the fingerprint you'll compare against later. Don't paste full assertion bodies or bearer tokens into a shared ticket.

  2. Remove the key from trust. SAML: delete the compromised <KeyDescriptor>/X509Certificate from the RP's trusted metadata, or disable the IdP connection. OIDC: drop the kid from the accepted JWKS, or point the RP at a JWKS you control. This is fail-closed: every in-flight token signed by that key now fails validation.

  3. Re-establish trust out-of-band. Get the new key or metadata over a channel you already trust: a call to a known contact, a signed email, a pre-shared fingerprint. Never fetch "new" metadata from the same URL that may have been tampered with.

  4. Invalidate what the old key could have minted. Revoke local sessions and refresh tokens, not just access tokens. OIDC refresh tokens routinely outlive the ID token by days, and revoking the signing key does nothing to them.

  5. Verify end to end, then restore gradually.

Trace: what removing a kid actually does. RP receives an ID token with header {"alg":"RS256","kid":"old-key-1"}. Cache has old-key-1, validation passes. After removal: lookup misses, RP refetches JWKS, old-key-1 is absent, validation fails, request returns 401. That 401 is the signal the removal took effect, and the signal that any RP still returning 200 is still trusting the old key.

Trade-off: remove now vs. overlap.

OptionEffectChoose when
Remove key now (fail-closed)All tokens signed by the old key rejected; live sessions breakKey confirmed compromised
Keep key with overlapAttacker keeps minting ability for the overlapOnly if compromise is unconfirmed and outage cost dominates

Failure modes and how to detect them.

  • Stale metadata cache. SAML metadata carries cacheDuration/validUntil; JWKS caches are often 5–10 minutes, some until a kid miss. Rotate but leave a cache warm and the RP keeps trusting the old key. Detect: assertion validation still succeeding against the old fingerprint in logs. Fix: force cache flush or restart.
  • XML signature wrapping (XSW). A valid signature is kept but moved to wrap a forged assertion. Detect: assert the signed element is the assertion you consume, and that IDs are unique.
  • Algorithm downgrade. RSA-SHA1 accepted alongside SHA-256. Detect: log the signature algorithm; alert on anything below SHA-256.
  • Refresh-token survival. Detect: a refresh grant succeeding after rotation.

Exposure arithmetic (hypothetical). ID token lifetime 1 h, detection lag 20 min. Tokens minted at T−59 min stay valid until T+1 min, so blast radius is bounded by token lifetime plus detection lag, not by session length. That is why you revoke sessions too: a 8 h RP session would otherwise outlive the token by hours.

When not to do this. If you're the IdP rotating keys, don't remove the old key unilaterally: RPs cache metadata for hours and you'll cause a mass outage. Publish the new key, wait out the cache window, then retire the old one.

Curated: · Written: · Reviewed:

Difficulty: Hard