Identity, Authentication, and Access Management Questions
Designing and operating identity and access control systems. Covers authentication protocols and standards (OAuth, SAML, OIDC, MFA), authorization models (RBAC, ABAC), identity lifecycle and privilege management, IAM architecture and automation, and access control across cloud and on-premises environments. The 'who can do what' control plane, distinct from cryptographic key management.
You're designing RBAC for a three-tier application (frontend, API/backend, data). Define a minimal set of roles (admin, developer, viewer) and map which permissions each role should have across compute, databases, object storage, and CI/CD. Describe constraints you would add (time-bound access, IP restrictions, MFA) and how you would test these roles before production rollout.
Sample Answer
Direct answer
Start with exactly three roles, admin, developer, and viewer, map each one's permissions across the four resource categories the application actually spans (compute, databases, object storage, and CI/CD, continuous integration and continuous delivery), layer time-bound access, IP restrictions, and multi-factor authentication (MFA) on top of the roles as separate constraints rather than baking them into the role definitions, and validate the roles with automated policy tests plus a staged dry run before they ever touch production.
Structured elaboration
Minimal role set and permission mapping.
| Resource | Admin | Developer | Viewer |
|---|---|---|---|
| Compute | Full manage (start/stop/configure, all environments) | Deploy/restart in non-production only; no production infrastructure changes | Read-only status across all environments |
| Databases | Schema changes, backups, user management | Read/write on non-production data; read-only on production | Read-only, all environments |
| Object storage | Create/delete buckets, manage bucket policies | Read/write on their team's non-production buckets | Read-only |
| CI/CD | Trigger and approve production deployments, manage pipeline config and secrets | Trigger builds and deploy to non-production stages; cannot approve or execute production deploys | Read pipeline status and logs only, no access to stored secrets |
The developer role is deliberately kept out of production-write access and out of approving its own production deployments; that separation of duties is what keeps the role useful without needing a fourth, more privileged role for most day-to-day work.
Constraints layered on top of the roles. Time-bound access: issue admin-level or production-touching grants through just-in-time elevation, a short, explicitly time-boxed session (for example four hours) requested for a specific reason and expiring automatically, rather than a standing permanent grant; a request-scoped elevation is a far smaller target than a permanent one. IP restrictions: condition production-write actions, especially CI/CD deployment triggers and database administration, on the request originating from a known, trusted network range such as a corporate VPN egress or the CI runner's own IP range, so a leaked credential alone isn't sufficient from an arbitrary location. Multi-factor authentication: require it specifically for anything in the admin role and for any elevation into a higher role, but not necessarily for routine viewer-level reads, since forcing it on every single read call adds friction without a matching security benefit; the real risk concentrates in the write and admin paths.
Testing before production rollout. Write automated policy tests that assert the boundaries directly, for example "the developer role cannot delete a production database," "the viewer role cannot write to any object storage bucket," and run them against the actual role definitions in a staging environment before applying anything to production; trusting a manual read-through of the policy document to catch these cases is how a subtle over-grant survives review. Beyond automated tests, roll the new role definitions out to a non-production environment first and have each role's real holder attempt their actual day-to-day tasks under the new definitions, a dry run that catches the specific failure mode where tightening a role inadvertently blocks a developer's own legitimate workflow, before that surprise happens in production instead.
Worked example
A policy test suite for this role set would include assertions along these lines, checked against a staging copy of the actual role definitions before they're applied to production:
- Assert
developerrole denieddatabase:dropTableon any resource taggedenvironment=production. - Assert
developerrole allowedstorage:writeonly on buckets tagged with that developer's own team. - Assert
viewerrole denied all*:writeand*:deleteactions across every resource category. - Assert
adminrole actions requiringenvironment=productionalso require an active MFA-verified session no older than a defined threshold.
Running this suite against the staging role definitions before promotion catches, for example, a developer role accidentally granted storage:delete through an overly broad wildcard permission, before that grant ever reaches production.
Trade-offs and pitfalls
Three roles is a deliberately minimal starting point: as the team grows, the developer role usually needs splitting, for example a database-focused developer versus a frontend-focused one, rather than the app growing a fourth, broader role too early, which adds administrative overhead before it's actually earned. A specific pitfall: giving the viewer role blanket "read" access to CI/CD without excluding stored secrets, since read access to pipeline configuration and read access to a secret value are not the same permission and should never be granted together by accident. Another: applying IP restrictions aggressively enough that legitimate remote or on-call access gets blocked with no documented break-glass path for the case where someone genuinely needs access from outside the usual network. The core trade-off in testing: a full staging dry run costs real time before every rollout, but skipping it is exactly how a well-intentioned role tightening breaks someone's legitimate daily workflow in production instead of catching it safely beforehand.
Perform a threat model for TOTP (time-based one-time password) second-factor authentication. Identify how replay attacks, desynchronization, brute-force guessing, provisioning interception, and man-in-the-middle attacks could be executed. Recommend mitigations such as skew windows, rate limiting, provisioning protections, and binding tokens to sessions or devices.
Sample Answer
Direct answer
A TOTP (time-based one-time password) second factor is a shared-secret HMAC construction where both the device and the server derive the same 6 to 8 digit code from a secret seed and the current time step, so the two sides never exchange the code over the network in a way an attacker can intercept and reuse indefinitely. The threat model has five concrete attack surfaces: replay of a captured code, clock desynchronization between device and server, brute-force guessing of the short code space, interception of the QR code or seed during provisioning, and man-in-the-middle (MITM) relay of a live code to a second, attacker-controlled session. Each has a standard, well-understood mitigation: single-use enforcement plus a bounded time-skew window, rate limiting with lockout, provisioning-time protections (short-lived enrollment links, out-of-band confirmation), and binding the verified factor to the session it was presented in so a stolen code cannot be replayed into a different session.
Structured elaboration
TOTP is defined by RFC 6238 (time-based) on top of RFC 4226's HOTP (HMAC-based one-time password): both endpoints hold a shared secret K, compute HOTP(K, T) where T is the number of 30-second time steps since the Unix epoch, and truncate the HMAC output to a short decimal code. The server never needs the code in advance because it can recompute it itself from the same seed and the current time; that is what makes threat-modeling this mechanism different from, say, a password, where the server must not know the plaintext at all.
Go through each named attack in turn:
-
Replay attacks. An attacker who observes a valid code (shoulder-surfing, malicious browser extension, compromised log line, or a MITM proxy) can submit it again. Because HOTP/TOTP codes are deterministic per time step, a naive server that only checks "does this code match the expected value" is replayable within that step.
- Mitigation: the server must record the last successfully consumed time step per user and reject any code at or before that step, even if it is otherwise numerically valid. This makes each code single-use regardless of the skew window discussed next.
-
Desynchronization. Device clocks drift. If the client's clock is even one 30-second step ahead or behind the server's, verification fails even for a legitimate user, which pushes real deployments to accept a window of adjacent steps (commonly ±1, sometimes ±2).
- Mitigation: a bounded skew window, and separately, per-user clock drift tracking: if a user consistently verifies at step +1, the server can persist that offset and auto-correct on subsequent checks instead of widening the window for everyone. Widening the window blindly is itself a security cost (see trade-offs below), so per-user drift correction is the senior answer, not just "increase the window."
-
Brute-force guessing. A 6-digit code has 1,000,000 possible values. Guessing has decent odds if an attacker can throw many attempts at the verification endpoint before the window rolls over: with no rate limiting, that is a live risk within a 30 to 90 second acceptance window.
- Mitigation: rate limiting and lockout at the verification endpoint (both per-account and per-source-IP), scoped tightly enough that 30 seconds of guessing cannot realistically cover a meaningful fraction of the code space. A common concrete rule: lock the factor after 5 to 10 consecutive failures, with exponential backoff, and alert on repeated failure bursts as a signal distinct from a single mistyped code.
-
Provisioning interception. Enrollment is the highest-value target: whoever gets the shared secret
Kduring setup, typically delivered as a QR code or a displayed base32 string, gets a permanent, silent second factor that behaves identically to the real one. Intercepting the QR code (screen capture, shoulder-surf during enrollment, a compromised enrollment email or support channel) is strictly worse than replaying one code, because it is not single-use.- Mitigation: enrollment must happen inside an already-authenticated, short-lived session (the QR code should expire in minutes, not persist on a settings page indefinitely), should never be emailed or logged in plaintext, and ideally requires a fresh primary-factor re-authentication immediately before the secret is displayed. Enrollment/re-enrollment events should also notify the user out of band (email or existing verified channel) so a silent re-enrollment by an attacker who has already compromised the account gets caught.
-
Man-in-the-middle (MITM) relay. This is the attack TOTP fundamentally cannot stop on its own: a phishing proxy sits between the user and the real site, and forwards both the password and the live TOTP code to the real site in real time. Because the code itself is valid, the server has no way to distinguish "the legitimate user typed this into the real site" from "the legitimate user typed this into a phishing clone that is relaying it."
- Mitigation: TOTP alone cannot close this gap; it needs to be paired with something that binds the session. Binding the verified MFA event to the session it was presented in (session ID or device fingerprint checked at the time of code submission, not just at login) limits how far a relayed code can travel, and detecting anomalous properties of the session (new device, new IP, new user agent, immediately following the MFA check) lets the server challenge again or flag the session even though the code itself was "correct." The durable fix for phishing-relay is moving to a phishing-resistant factor (WebAuthn/FIDO2), which cryptographically binds the credential to the origin.
Worked example
Take a concrete deployment: 30-second time steps, a ±1 step skew window (accepts the previous, current, and next step, so 90 seconds of nominal acceptance), and a rate limit of 5 attempts per 5 minutes per account.
- Replay defense in numbers: without single-use enforcement, an attacker who captures one valid code has up to 90 seconds (three accepted steps) to reuse it. With single-use-per-step-consumed enforcement, that window collapses to zero: the moment the legitimate user's code is accepted, the server marks that step (and everything before it) as spent, so a captured copy of the same code is rejected even if submitted one second later.
- Brute-force defense in numbers: the code space is 10^6 = 1,000,000 values. At 5 attempts per 5 minutes, an attacker can try at most 5 values inside any single 90-second acceptance window before the account locks, a success probability of 5 / 1,000,000 = 0.0005% per window, not a meaningful attack path. Contrast that with no rate limiting: at a realistic 50 requests/second against an unprotected endpoint, an attacker could submit roughly 50 x 90 = 4,500 guesses inside one 90-second window, a success probability of 4,500 / 1,000,000 = 0.45% per attempt window, and the attacker gets a fresh window every 30 seconds indefinitely. That four-orders-of-magnitude gap is the entire argument for rate limiting existing at all.
- Session-binding defense against relay: if the server records the session identifier present when the TOTP code was submitted and requires the subsequent authenticated request to reuse that same session (rather than accepting the code as a standing "MFA satisfied" flag that any session can claim), a phishing proxy that relays the code into its own attacker-controlled session is blocked at the point the attacker tries to use the resulting authenticated state, because the session the attacker holds never received the MFA check itself.
Trade-offs and pitfalls
- Skew window width is a direct trade-off between usability and brute-force exposure. A wider window (say ±5 steps, 5.5 minutes) tolerates more clock drift and slow typers but multiplies the number of valid codes an attacker can guess against at any instant; senior designs prefer a narrow window plus per-user drift correction over a blanket wide window.
- Rate limiting must be per-account AND per-source, not just one or the other: per-account-only limiting still lets an attacker distribute guesses across many source IPs against one account without tripping IP-based defenses, and per-IP-only limiting misses a slow, patient attacker rotating targets.
- The common pitfall is treating "MFA passed" as a permanent session attribute instead of a check tied to the specific session and, ideally, request context; that is exactly what lets a relayed code from a phishing proxy grant the attacker's own session indefinite access once the real user's code is forwarded through it once.
- Provisioning is the highest-leverage place to under-invest, because a compromised enrollment is silent and permanent until discovered, unlike a single replayed code which is a one-time, noisy event; teams that harden verification but leave enrollment on a long-lived, unauthenticated, or loggable path have not actually raised the bar much.
- TOTP cannot solve phishing-relay by construction, since the whole point of the shared time-based secret is that it produces a value valid for anyone who submits it in time; acknowledging this honestly (rather than claiming "MFA stops phishing") is itself part of a mature threat model.
Explain the principle of least privilege and provide a concrete example applying it to API permission design for an enterprise application. Identify entities involved, the minimal permissions you would grant, how you would enforce validation, and how you'd monitor and detect over-provisioned permissions.
Sample Answer
Direct answer
Least privilege means every identity, human or machine, is granted only the permissions its current task actually requires, nothing broader "just in case," and that grant is re-evaluated as the task changes rather than left in place indefinitely. Applied to API (application programming interface) permission design, it means scoping each credential or token to the exact operations and resources one endpoint needs, never issuing one broad, reusable key that happens to also work everywhere else.
Structured elaboration
Entities involved. Three distinct parties matter in almost any API call: the end user on whose behalf the request is made, the calling client or service application making the request, and any further downstream service the API itself calls to fulfill it. Least privilege has to be applied at each link in that chain, not just the outermost one; an API that carefully scopes what the end user can request but then calls a downstream service with a broad, unscoped internal credential has only solved part of the problem.
Minimal permissions. Take a concrete case: a "get order status" endpoint needs read-only access to the orders data, scoped specifically to the orders belonging to the requesting user, not to all orders and not write access to any of them. Design that as its own explicit permission, for example orders:read:self, rather than reusing a broader orders:* credential that some other, more privileged internal tool happens to already have; reuse for convenience is exactly how an unrelated endpoint quietly ends up more privileged than it needs to be.
Enforcing validation. Authorization has to be checked at the point of use, and it has to check two things, not one: that the token's scope permits this kind of operation at all, and that the specific resource being requested (this particular order ID) actually belongs to the requesting user. Scope alone is not enough, since a valid orders:read:self token still says nothing about whether order 4471 belongs to the user presenting it; a code path that checks only the scope and forgets the object-level ownership check will happily let one user read another user's order. The default should fail closed: deny unless a check explicitly passes, on every request, not only at initial login.
Monitoring and detecting over-provisioning. The useful signal is not what a credential was granted, but what it actually uses. Log which scopes are genuinely invoked over a rolling window, for example ninety days, and flag any credential holding a scope that window never exercised: a granted-but-unused broad scope is precisely the residual risk least privilege exists to eliminate. Periodic, automated comparison of granted versus actually-used permissions, with drift raised for review, turns this from a one-time design exercise into an ongoing discipline.
Worked example
Suppose an internal reporting service was originally granted orders:*, covering read, write, and delete across every order, because that was the fastest way to get it working at the time. A ninety-day audit of the API gateway's access logs for that service's credential shows the following actual call counts:
| Scope exercised | Calls over 90 days |
|---|---|
orders:read (via GET /orders) | 48,213 |
orders:write | 0 |
orders:delete | 0 |
Given that write and delete were invoked zero times across the full window, the credential is narrowed to orders:read alone, and the removed scopes are confirmed with the team that owns the reporting service before the change ships, in case an unexercised capability was intentionally held in reserve for a not-yet-built feature. This table is illustrative of the audit reasoning, not a claim about any specific real system's logs.
Trade-offs and pitfalls
The most common real-world failure is granting a broad scope simply to move faster during initial development, with the intention of "narrowing it later," a step that in practice rarely happens without an explicit process forcing it, which is exactly what the periodic use-versus-grant audit provides. A closely related pitfall is checking authorization only at the coarse scope level and skipping the object-level ownership check, which is how a technically-scoped API still lets one user access another user's specific resource. The underlying trade-off is administrative: fine-grained, per-endpoint scopes are more secure but create more distinct permissions to define, document, and keep track of, while a coarser scope model is easier to administer but concedes more of the least-privilege guarantee than it should.
List practical techniques to minimize the blast radius if an access token is leaked (for example via logs or a browser extension). Discuss token scope reduction, short-lived tokens, refresh rotation, token binding, IP/device restrictions, and monitoring/detection strategies:explain trade-offs for usability and complexity.
Sample Answer
Direct answer
No single technique fully neutralizes a leaked access token; the practical goal is to stack several independent mitigations so a leak (say, via an application log line or a malicious browser extension reading page requests) costs an attacker as little as possible, for as short a time as possible, and gets noticed quickly. The six techniques below each shrink a different dimension of the damage: what the token can do, how long it stays useful, whether it can be silently reused, and how fast anyone finds out it was stolen.
Structured elaboration
| Technique | What it limits | Usability / complexity cost |
|---|---|---|
| Token scope reduction | Issue a token with only the specific permissions the current operation needs, not the user's full entitlement set | Requires the client to request narrower scopes per use case rather than one broad token, adding request-design work up front |
| Short-lived tokens | Bounds how long a leaked token remains usable before it expires on its own | More frequent refresh calls, adding a small but real latency/load cost |
| Refresh token rotation | Makes a stolen refresh token detectable (and revocable) the moment both the attacker and the legitimate client try to use it, rather than letting it be silently reused indefinitely | Requires server-side state to track the current valid identifier per session, and careful handling of legitimate client retries so they are not mistaken for reuse |
| Token binding (proof of possession) | Ties the token to a specific device or key, so a copied token string alone is useless without also holding the bound private key | Meaningfully harder to implement (device-held keys, signed proofs per request) and not universally supported across all client platforms |
| IP / device restrictions | Rejects use of a valid token from an unexpected IP address or device fingerprint | Real usability cost for legitimate users on shared networks, VPNs, or carrier-grade NAT, where the "expected" IP genuinely changes; needs to be a soft signal, not a hard block, to avoid locking out real users |
| Monitoring and detection | Does not prevent theft, but shortens the time between a leak happening and someone noticing (unusual access patterns, geographically implausible reuse, sudden scope escalation attempts) | Requires building and tuning detection logic, and accepting some false positives as the cost of catching true ones |
None of these is sufficient alone: scope reduction limits damage from a token that is never revoked at all, but a narrowly-scoped token that leaks and lives for 90 days is still a 90-day exposure; short-lived tokens bound the exposure window but do nothing if the attacker keeps re-obtaining fresh tokens through a still-valid refresh token; token binding stops replay of a copied token string but does not help if the underlying device itself is compromised. The combination is what actually reduces blast radius: a short-lived, narrowly-scoped, bound token, refreshed through a rotating refresh token, with anomaly detection watching for whatever slips through.
Worked example
An access token is accidentally written to an application log (a real, common leak vector) and later exfiltrated by whoever gains read access to those logs, days after the log entry was written.
- Without any mitigation: the token, if long-lived and broadly scoped, remains fully usable for its entire original lifetime, granting the same access the legitimate user had, indistinguishable from a real request.
- With scope reduction alone: the leaked token can only perform the narrow operation it was issued for (say, "read this one resource"), not the user's full account access, but that narrow access remains available for the token's full remaining lifetime.
- With short-lived tokens added: the exposure window shrinks to whatever remains of the token's short lifetime by the time the log is read; a token minted hours before the log leak has likely already expired by the time an attacker acts on it days later.
- With token binding added on top: even a token that has not yet expired is useless to the log-reading attacker, since they do not also hold the private key it was bound to; the leaked string alone cannot be replayed.
- With monitoring layered over all of the above: even the narrow residual risk (an attacker who somehow also compromises the binding, or catches a token in its live window) generates an anomaly signal (an unfamiliar IP, an unusual access pattern) that triggers an alert and a manual or automatic revocation, closing the gap the other layers could not close analytically.
Trade-offs and pitfalls
The common pitfall is picking one mitigation (usually short-lived tokens, since it is the easiest to implement) and treating the blast-radius problem as solved, without also budgeting the operational cost of the others. IP restriction in particular is the technique most likely to backfire if applied too strictly: mobile users change IP addresses routinely as they move between cell towers and Wi-Fi networks, and a hard block on IP change will generate real support burden and locked-out legitimate users rather than meaningfully stopping a sophisticated attacker, who can often route through a similar geography anyway. The right calibration is almost always defense in depth with graduated response (soft signals feeding monitoring and step-up authentication, rather than every mitigation being a hard block), because a security control that is too disruptive to real users gets quietly disabled by the product team the first time it causes a support incident, which is worse than never having shipped it.
In Node.js using Express, outline middleware that verifies a Bearer JWT access token signed with RS256 by using a JWKS endpoint. Provide the high-level pseudocode, list error cases to handle (expired, malformed, unknown kid), and explain how to cache JWKS keys safely to avoid performance problems.
Sample Answer
Direct answer
An Express middleware that verifies a Bearer RS256 JWT (JSON Web Token) needs to: extract the token from the Authorization header, resolve the signing key by the token's kid from a JWKS (JSON Web Key Set) endpoint through a caching client rather than fetching on every request, verify the signature with the algorithm pinned to RS256, and map each distinct failure (missing header, malformed token, expired token, unknown kid) to a 401 response with its own machine-readable error code, so logs and clients can tell the failure modes apart instead of seeing one undifferentiated "unauthorized."
Structured elaboration (approach)
- Extraction: read
Authorization: Bearer <token>; a missing or malformed header is rejected before any verification work happens at all. - Key resolution with caching: use a JWKS client (
jwks-rsabelow) configured withcache: true, acacheMaxAge, andrateLimit: truewith a requests-per-minute ceiling. This matters specifically because a burst of requests can present several differentkidvalues in quick succession right after the identity provider rotates keys; without a cache, that burst becomes a burst of outbound calls to the JWKS endpoint, turning someone else's infrastructure into a dependency of your hot path. - Verification:
algorithms: ['RS256']is passed explicitly, the same defense used against algorithm-confusion attacks as in a Python implementation of the same idea, plusaudienceandissuerchecks and aclockTolerancefor clock-skew. - Error mapping:
TokenExpiredErrorbecomestoken_expired;JsonWebTokenError(which covers a malformed token and a bad signature) becomesinvalid_token; anything else, in practice the JWKS client's own "no signing key found for this kid" error, becomesunauthorized.
Worked example (executed)
"use strict";
const http = require("http");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const jwksClient = require("jwks-rsa");
// npm install jsonwebtoken jwks-rsa
const EXPECTED_ISSUER = "https://idp.example.com";
const EXPECTED_AUDIENCE = "orders-api";
function requireBearerJwt(client) {
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
if (err) return callback(err);
callback(null, key.getPublicKey());
});
}
return function (req, res, next) {
const authHeader = req.headers["authorization"] || "";
const match = /^Bearer (.+)$/.exec(authHeader);
if (!match) {
return res.status(401).json({ error: "missing_bearer_token" });
}
const token = match[1];
jwt.verify(
token,
getKey,
{
algorithms: ["RS256"],
audience: EXPECTED_AUDIENCE,
issuer: EXPECTED_ISSUER,
clockTolerance: 30,
},
(err, decoded) => {
if (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ error: "token_expired" });
}
if (err.name === "JsonWebTokenError") {
return res.status(401).json({ error: "invalid_token", detail: err.message });
}
return res.status(401).json({ error: "unauthorized", detail: err.message });
}
req.user = decoded;
next();
}
);
};
}
// --- test harness: real RSA keypair, real local JWKS HTTP server, 5 cases ---
function buildKeypairAndJwks() {
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
const jwk = publicKey.export({ format: "jwk" });
jwk.kid = "test-key-1";
jwk.alg = "RS256";
jwk.use = "sig";
return { privatePem: privateKey.export({ format: "pem", type: "pkcs8" }), jwksDoc: { keys: [jwk] } };
}
function startJwksServer(jwksDoc) {
const body = JSON.stringify(jwksDoc);
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(body);
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
const { port } = server.address();
resolve({ server, jwksUrl: `http://127.0.0.1:${port}/jwks.json` });
});
});
}
async function runCase(middleware, authHeaderValue) {
const req = { headers: { authorization: authHeaderValue } };
let nextCalled = false;
const settled = new Promise((resolve) => {
const res = {
_status: 200, _body: null,
status(code) { this._status = code; return this; },
json(body) { this._body = body; resolve(); return this; },
};
req._res = res;
middleware(req, res, () => { nextCalled = true; resolve(); });
});
await settled;
const res = req._res;
return { nextCalled, status: res._status, body: res._body, user: req.user };
}
async function main() {
const { privatePem, jwksDoc } = buildKeypairAndJwks();
const { server, jwksUrl } = await startJwksServer(jwksDoc);
const client = jwksClient({
jwksUri: jwksUrl, cache: true, cacheMaxEntries: 5,
cacheMaxAge: 10 * 60 * 1000, rateLimit: true, jwksRequestsPerMinute: 10,
});
const middleware = requireBearerJwt(client);
const now = Math.floor(Date.now() / 1000);
const basePayload = { sub: "user-42", iss: EXPECTED_ISSUER, aud: EXPECTED_AUDIENCE };
const validToken = jwt.sign(basePayload, privatePem, { algorithm: "RS256", keyid: "test-key-1", expiresIn: 300 });
const expiredToken = jwt.sign({ ...basePayload, iat: now - 1000, exp: now - 700 }, privatePem,
{ algorithm: "RS256", keyid: "test-key-1" });
const unknownKidToken = jwt.sign(basePayload, privatePem, { algorithm: "RS256", keyid: "does-not-exist", expiresIn: 300 });
const malformedToken = "not-a-jwt-at-all";
const results = [];
const r1 = await runCase(middleware, `Bearer ${validToken}`);
results.push(["valid token calls next() with req.user", r1.nextCalled && r1.user && r1.user.sub === "user-42"]);
const r2 = await runCase(middleware, `Bearer ${expiredToken}`);
results.push(["expired token -> 401 token_expired", !r2.nextCalled && r2.status === 401 && r2.body.error === "token_expired"]);
const r3 = await runCase(middleware, `Bearer ${malformedToken}`);
results.push(["malformed token -> 401", !r3.nextCalled && r3.status === 401]);
const r4 = await runCase(middleware, `Bearer ${unknownKidToken}`);
results.push(["unknown kid -> 401", !r4.nextCalled && r4.status === 401]);
const r5 = await runCase(middleware, "");
results.push(["missing bearer header -> 401 missing_bearer_token", !r5.nextCalled && r5.status === 401 && r5.body.error === "missing_bearer_token"]);
let allPass = true;
for (const [name, passed] of results) {
console.log(`[${passed ? "PASS" : "FAIL"}] ${name}`);
if (!passed) allPass = false;
}
console.log(`\nALL_PASS=${allPass}`);
server.close();
}
main();
Output, from an actual run (node verify_jwt_middleware.js):
[PASS] valid token calls next() with req.user
[PASS] expired token -> 401 token_expired
[PASS] malformed token -> 401
[PASS] unknown kid -> 401
[PASS] missing bearer header -> 401 missing_bearer_token
ALL_PASS=true
Complexity and edge cases
Excluding a JWKS cache miss (one HTTP round trip), each request costs one RSA signature verification and a handful of claim comparisons, O(1) in the number of requests. The three named error cases plus a missing-header case are exercised directly above: expired token, malformed token, and unknown kid all resolve to a 401 with a distinct error code rather than an unhandled exception or a generic 500, and each is tested against a real signature so the failure is genuine, not simulated by mocking the verification step itself.
Trade-offs and pitfalls
- Don't collapse "the credential is missing" and "the credential is invalid" into identical log output; both end up as a
401, but a client integration bug (forgetting the header) looks nothing like a compromised or expired token in an incident review, and conflating them in logs erases that distinction. - The JWKS client's cache has a maximum entry count; under a fleet-wide key rotation with many keys active simultaneously, a low limit can evict entries that are still legitimately in use, causing avoidable cache misses. Size it against how many keys the identity provider actually keeps active concurrently, not against a copied default.
getKeybeing asynchronous means a slow, uncached key lookup adds real latency to that one request, not to the whole server, but "not blocking everyone else" is a much lower bar than "fast." The cache configuration is what actually keeps the common case fast, not the mere fact that the lookup is async.
Unlock Full Question Bank
Get access to all Identity, Authentication, and Access Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.