API Security, Authentication and Authorization Questions
Controlling who can call an API, what they may do, and defending it against abuse. Covers the access-control mechanics: API keys, OAuth 2.0 flows, OpenID Connect, JWT issuance/validation, session vs. token auth, scopes/roles for fine-grained authorization, token lifetime and refresh, mutual TLS, and machine-to-machine vs. user-delegated access. Also covers the adversarial hardening view: input validation, injection and deserialization risks, broken object-level authorization (BOLA), mass assignment, secrets handling, and the OWASP API Security Top 10, plus securing data in transit, preventing enumeration/scraping, and testing APIs for vulnerabilities.
Build an authentication and authorization scheme for a multi-tenant API that supports bearer tokens for user auth and API keys for service-to-service calls. Include per-tenant rate limits, key rotation, revocation, secure key storage, and how to represent tenant scoping in tokens or claims.
Sample Answer
Represent the tenant as a first-class claim (tid) inside every bearer token, so the API gateway can enforce tenant isolation without an extra database lookup on the hot path, and treat API keys for service-to-service calls as a separate credential type: hashed at rest, bound to exactly one tenant at issuance, rotated by versioning rather than in-place mutation.
Two credential types, one enforcement point
- User bearer tokens: OAuth 2.0 Authorization Code flow (the user logs in and consents at the identity provider, which redirects back with a one-time code that the app then exchanges server-side for a token) issues a short-lived JSON Web Token (JWT), 5-15 minutes, with claims
sub(user id),tid(tenant id), androles/scopes. - Service API keys: a high-entropy key id plus secret, sent as
Authorization: ApiKey <id>.<secret>, stored hashed server-side (for example with Argon2id), with a metadata row mappingkey_id -> tenant_id, scopes, status. - Both paths terminate at one API gateway, which extracts a normalized identity and tenant context (
X-Tenant,X-Scopesheaders) and forwards it downstream, so backend services never re-implement auth.
Tenant scoping in tokens
Whether the credential is a JWT's tid claim or an API key's tenant_id metadata row, both resolve to the same enforcement check: every downstream query filters WHERE tenant_id = :tid, and the gateway rejects any request whose payload references a different tenant_id than the token's own, before it ever reaches business logic. This is the tenant-boundary version of the same defense used against broken object-level authorization (a caller reaching another user's specific record just by guessing or changing its id) at the user boundary.
Per-tenant rate limits
Use a token bucket keyed by tenant_id, not by individual API key, because a tenant with several service accounts should share one quota. A per-key-only limit lets a tenant multiply its effective throughput just by minting more keys. Store buckets in a shared cache (for example Redis) keyed tenant:{tid}, with the refill rate set per pricing tier.
Key rotation and revocation
API keys are versioned (key_id:v1, v2, ...). Rotation creates a new version ACTIVE, marks the old one DEPRECATED for a grace window, then REVOKED. The revocation list is cached at the gateway and refreshed on a short interval or via an event push. Signing keys for JWTs rotate through a published JWKS (JSON Web Key Set) endpoint with overlapping key IDs, so tokens signed with the outgoing key still validate until they naturally expire.
Secure key storage
API key secrets are hashed (never stored or logged in plaintext) and shown in cleartext exactly once, at creation. Signing keys live in a key management service (KMS) or hardware security module (HSM); application code never touches the private key material directly.
Worked example
Tenant acme (tid=acme-042) runs a service account calling a billing API at 40 requests/second peak. Rate-limit config: 50 requests/second sustained, burst 100. The token bucket starts at 100 tokens and refills at 50/second, each request consuming one token. At a sustained 40 req/sec, the bucket never empties (refill 50 exceeds consumption 40), so no throttling occurs. If acme mints a second service account and the two together push 90 req/sec, the shared tenant-level bucket still throttles correctly at 50 req/sec sustained, whereas a per-key-only limit of 50 each would have let the tenant reach 100 req/sec simply by adding a key, defeating the purpose of a tenant-level quota.
Trade-offs and pitfalls
Putting tid only in application logic (not the token) forces a lookup on every request; putting it in the token is faster, but a tenant reassignment then requires reissuing tokens rather than just updating a database row. API keys are simpler for automation but riskier if leaked, since they carry no built-in expiry, mitigate with short rotation cadence and IP allowlisting per key. The common pitfall shown above is rate-limiting per API key instead of per tenant, which lets a tenant multiply its effective quota by minting more keys.
Build automated tests to detect field level authorization bypass in a GraphQL service where some schema fields should only be visible to certain roles. Provide a practical test script example (for instance in Python or JavaScript) that: 1) enumerates accessible fields for an admin user, 2) repeats the same queries for a low privilege user, and 3) asserts unauthorized fields are absent or redacted. Explain how to handle schema introspection differences between environments.
Sample Answer
Direct answer
Test field-level authorization the same way you would test any access-control rule: run the
identical query as two different callers (a caller who should see a protected field and one who
should not) and assert on the difference. A GraphQL server that enforces field rules only in the
resolver, and not also in the schema's introspection output, will happily tell an unauthorized
caller a sensitive field exists even while refusing to return its value, so the test also needs
to work when introspection is turned off in an environment.
Structured elaboration
Why this is a distinct risk from REST-style object-level authorization. In a REST API you
typically authorize per endpoint or per object id. In GraphQL, a single query can request many
fields on an object in one call, and each field can have its own authorization rule (this is the
GraphQL-specific instance of what OWASP (the Open Web Application Security Project, a nonprofit that publishes ranked lists of common API and web vulnerability categories) calls, in its 2023 API Security Top 10, Broken Object Property
Level Authorization, API3:2023). It is easy to correctly gate the object as a whole (only the
owner can query user(id)) while forgetting that one of its fields, say ssn or
internalRiskScore, should be admin-only regardless of who owns the parent object.
Building the test:
- Enumerate the fields to check. In an environment where introspection is enabled, query
the schema itself to get the full field list for the type under test. In production-like
environments introspection is usually disabled as a hardening step, so the test needs a
fallback: a checked-in SDL (schema definition language) snapshot of the type, kept current by
a CI check that diffs it against the schema whenever the schema changes. Do not let "no
introspection here" become "no test coverage here." - Run the query as the high-privilege caller and record which fields came back populated.
This is your baseline of what the type is supposed to expose to someone with full access. - Run the identical query shape as the low-privilege caller.
- Assert on the difference, not just on errors. Many GraphQL servers do not reject the
whole request when a caller cannot read one field; they returnnullfor that field plus an
entry in the response'serrorsarray (a "partial success"). A test that only checks the top
level HTTP status code, or only checks for the presence of an error, will miss a server that
silently returns the real value instead ofnull. Assert directly that every field which
should be role-gated is either absent,null, or explicitly redacted in the low-privilege
response, and separately assert that fields which should be visible did not regress.
Worked example
# Field-level authorization test for a GraphQL API.
#
# In real CI this would POST to a live endpoint (e.g. with `requests` or `gql`),
# sending the query with an admin token, then again with a low-privilege token.
# To keep this example runnable with no network dependency, the "server" below
# is a tiny in-process resolver enforcing the same rule a real GraphQL server
# would via a per-field `@auth(role: ...)` directive: it nulls out any field
# the caller's role does not satisfy. The test logic (enumerate -> re-run as
# low-priv -> assert unauthorized fields absent) is exactly what you would run
# against a live endpoint.
FIELD_ROLES = {
"id": None,
"email": None,
"fullName": None,
"ssn": "ADMIN",
"internalRiskScore": "ADMIN",
"billingAddress": "ADMIN",
}
USER_RECORD = {
"id": "u-42",
"email": "jane@example.com",
"fullName": "Jane Doe",
"ssn": "123-45-6789",
"internalRiskScore": 87,
"billingAddress": "1 Market St",
}
def execute_query(fields, role):
# Returns the same shape a real GraphQL response would: unauthorized
# fields come back null with an entry in `errors`, matching how most
# GraphQL servers signal a partial-authorization failure.
data, errors = {}, []
for f in fields:
required = FIELD_ROLES[f]
if required is None or required == role:
data[f] = USER_RECORD[f]
else:
data[f] = None
errors.append(f"not authorized to read field '{f}'")
return {"data": data, "errors": errors}
def schema_fields_for_type(type_name, introspection_enabled=True):
# Falls back to a checked-in SDL snapshot when introspection is disabled
# (a common prod hardening step), instead of depending on a live
# introspection query that only works in dev/staging.
return list(FIELD_ROLES.keys())
def test_field_level_authorization_bypass():
all_fields = schema_fields_for_type("User", introspection_enabled=True)
# 1) enumerate what an admin can see
admin_response = execute_query(all_fields, role="ADMIN")
admin_visible = {f for f, v in admin_response["data"].items() if v is not None}
assert admin_visible == set(all_fields)
# 2) repeat the identical query shape for a low-privilege caller
user_response = execute_query(all_fields, role="USER")
user_visible = {f for f, v in user_response["data"].items() if v is not None}
# 3) assert every admin-only field is absent (redacted to null) for the low-priv caller
admin_only_fields = {f for f, req in FIELD_ROLES.items() if req == "ADMIN"}
leaked = admin_only_fields & user_visible
assert not leaked, f"low-privilege caller could read admin-only fields: {leaked}"
public_fields = set(all_fields) - admin_only_fields
assert public_fields <= user_visible
return {
"admin_visible": sorted(admin_visible),
"user_visible": sorted(user_visible),
"admin_only_fields_blocked_for_user": sorted(admin_only_fields),
"user_errors": user_response["errors"],
}
result = test_field_level_authorization_bypass()
print("admin_visible:", result["admin_visible"])
print("user_visible:", result["user_visible"])
print("admin_only_fields_blocked_for_user:", result["admin_only_fields_blocked_for_user"])
print("user_errors:", result["user_errors"])
print("PASS: no admin-only field leaked to the low-privilege caller")
Output:
admin_visible: ['billingAddress', 'email', 'fullName', 'id', 'internalRiskScore', 'ssn']
user_visible: ['email', 'fullName', 'id']
admin_only_fields_blocked_for_user: ['billingAddress', 'internalRiskScore', 'ssn']
user_errors: ["not authorized to read field 'ssn'", "not authorized to read field 'internalRiskScore'", "not authorized to read field 'billingAddress'"]
PASS: no admin-only field leaked to the low-privilege caller
The admin caller sees all 6 fields; the low-privilege caller sees only the 3 public fields, and
the 3 admin-only fields (ssn, internalRiskScore, billingAddress) come back null with a
matching error. A bug that forgot to gate one of those fields would flip that field from null
into user_visible, and the assertion on leaked would fail immediately, which is the exact
regression this test is designed to catch.
Trade-offs and pitfalls
Handling schema introspection differences between environments. Many teams disable
introspection in production for defense-in-depth, but leave it on in staging or dev. If your
test only discovers the field list by querying introspection live, it silently stops running in
the one environment where you most need it. Keep a versioned SDL snapshot as the source of truth
for "what fields exist," and add a separate, lightweight CI check that fails whenever a live
introspection query (in an environment where it is enabled) diverges from the snapshot, so the
snapshot itself cannot go stale.
Pitfall: testing only the object, not its fields. A team that already has a BOLA (Broken Object Level Authorization, OWASP API1:2023, a different category from the object-property-level one described earlier in this answer) style test
("user A cannot fetch user B's record") sometimes assumes field-level authorization is covered
by the same test. It is not: BOLA is about whose object you can reach, field-level
authorization is about which parts of an object you can see once you can reach it, and a
caller can legitimately own the object (their own profile) while still not being entitled to
every field on it (an internal risk score, say). Test the two separately.
Pitfall: asserting on HTTP status only. GraphQL servers conventionally return HTTP 200 even
for partially-authorized or partially-failed responses, with the real signal inside the response
body's data and errors. A test suite carried over from REST-style thinking that only checks
response.status_code == 200 will pass even when a field-level authorization bug leaks real
data, because the status code never changes.
Given a GraphQL mutation that accepts deeply nested input to create users and related resources, perform a threat model that focuses on injection, excessive data exposure, denial-of-service via complex nested queries, and authorization bypass. Propose precise mitigations such as sanitization, field-level authorization hooks, depth/complexity limiting, persisted queries and cost estimation.
Sample Answer
Direct answer
For a GraphQL mutation that accepts deeply nested input to create users and related resources,
the threat model has four connected risks: injection through any field that reaches a data
store or downstream system, excessive data exposure through the response shape a single query
can request, denial-of-service through the cost of resolving deeply nested or high-fan-out
selections, and authorization bypass at the object and field level within the nested structure,
not just at the mutation's top-level entry point. Because a single GraphQL request can touch
many resources and relationships in one call, each of these risks compounds with nesting depth
in a way a single flat REST endpoint does not.
Structured elaboration
Injection. Every leaf value in the nested input (a related resource's name, an address
field several levels deep) is still untrusted input reaching business logic and, eventually,
storage; the nesting does not change the injection risk, it just multiplies how many fields need
the same discipline applied consistently: parameterized queries, never string-built ones, plus
strict schema validation on every nested object (not only the mutation's top-level arguments,
which is where a reviewer's eye is naturally drawn) and correct output encoding wherever any of
this data is later rendered back out.
Excessive data exposure. Because the same mutation can request a return shape that includes
newly created and related resources, a response can overfetch: it can return internal or
sensitive fields on those related resources that the caller was never meant to see, simply
because the schema allows selecting them and nobody scoped the mutation's response shape as
carefully as its input shape was scoped. Mitigate this the same way field-level authorization
is enforced on queries: role- and ownership-aware field resolvers on the response type, not an
assumption that "this is a write endpoint, so read-side authorization doesn't apply here."
Denial-of-service via complex nested queries. A mutation with deeply nested input, or a
follow-up query selecting deeply nested relationships, can force the server to do
exponentially more work than the request's size on the wire suggests, since each level of
nesting can multiply the resolvers invoked by the requested page size at that level. Mitigate
with depth limiting (rejecting a query or mutation whose selection nests deeper than a configured
maximum) and query complexity/cost analysis (assigning each field a cost, multiplying by
requested list sizes at each level, and rejecting a request whose total cost exceeds a budget
before executing any of it).
Authorization bypass. A nested mutation creating multiple related resources in one call needs
authorization checked at every object being created or referenced, not only at the top-level
"can this user call this mutation at all" gate; a caller authorized to create their own user
profile is not automatically authorized to attach that profile to an organization they do not
belong to, simply because the organization reference is buried three levels into the nested
input rather than being the mutation's top-level argument.
Concrete mitigations, tied to the risks above:
- Sanitization and parameterization at every leaf field, same discipline as any other
user-supplied input reaching a data store. - Field-level authorization hooks on both the input side (can this caller set this field or
reference this related object) and the response side (can this caller see this field on the
result), not only on the mutation as a whole. - Depth and complexity limiting, rejecting requests that exceed a configured nesting depth
or computed cost before execution begins, so a malicious request is rejected cheaply rather
than partially executed before being caught. - Persisted queries (the client sends a reference to a pre-registered, pre-approved query
shape rather than an arbitrary ad-hoc query string), which is a strong mitigation against
unexpected malicious query shapes specifically, since the server only ever executes shapes it
already reviewed and approved, though it does not by itself replace per-request authorization
checks on the data those approved shapes touch. - Cost estimation, the mechanism underlying complexity limiting: assign a numeric cost to
each field (higher for fields that fan out via a list) so the total cost of a specific request
can be computed and compared against a budget before execution.
Operational testing to validate the mitigations. These protections need to be verified the
same way any other security control is verified, with automated tests exercising the negative
cases: a test that submits a mutation nested one level past the configured depth limit and
asserts it is rejected before any database write occurs; a test computing a request's expected
cost against the cost model and asserting the server's rejection threshold matches; and a
field-level authorization test that runs the identical nested mutation as two different callers
(one entitled to set or see a given nested field or object, one not) and asserts the
unauthorized caller's attempt is rejected or the field comes back redacted, since a passing
depth-limit test says nothing about whether the authorization checks inside that depth are
actually being enforced.
Overfetching and introspection abuse, as related but distinct concerns. Overfetching (a
client requesting far more of the graph than its use case needs, even without malicious intent)
is a milder version of the excessive-data-exposure risk above and is best addressed by the same
field-level authorization plus reasonable default response shapes; introspection abuse (an
attacker using the schema's own introspection query to map out the entire graph, including
fields or types not intended for public discovery, as reconnaissance for a later attack) is
mitigated by disabling introspection in production, backed by a checked-in schema snapshot so
tooling and tests still have a field list to work from, or, where some introspection must stay
available, at minimum excluding internal-only types and fields from it.
Worked example
Consider a nested mutation: user { id, posts(first: 20) { id, comments(first: 20) { id } } }.
Using a simple cost model where a scalar field costs 1 point per row in scope and a list field
multiplies the cost of everything beneath it by the requested page size:
user.id : 1 (scope multiplier 1)
user.posts (node) : 1 (scope multiplier 1, before its own multiplier applies)
posts.id : 20 (scope multiplier 20, from posts' page size)
posts.comments (node) : 20 (scope multiplier 20)
comments.id : 400 (scope multiplier 20 * 20, nested page sizes compound)
-----------------------------------------------
total cost : 442
If the server enforces a cost budget of, say, 300 per request, this query is rejected before
execution, purely from its declared shape, with no database call made. Without complexity
limiting, a client (or attacker) could push first: 100 at each level instead of first: 20,
pushing the comments.id term alone to 100 * 100 = 10,000, a strictly wire-cheap request that
would force the server to resolve tens of thousands of rows.
Trade-offs and pitfalls
- Depth and complexity limits are blunt instruments that can reject legitimate, unusually
shaped requests, not just malicious ones; calibrate the budget against your real schema's
legitimate worst-case use cases, and expose a documented way for a legitimate client with a
genuinely larger need to request a higher limit, the same way an API rate-limit exception
process should exist. - Persisted queries strongly constrain query shape but do nothing about authorization on the
data a shape touches; a persisted query approved months ago can still be misused by a
caller who should not have access to the specific objects it happens to reference this time, so
persisted queries reduce, but do not replace, per-request field- and object-level authorization. - Common wrong turn: authorizing only the mutation's top-level entry point. A nested mutation
is not one flat authorization check, it is potentially many, one per object being created or
referenced within the nested input, and skipping the nested ones is exactly the authorization-
bypass risk this threat model calls out. - Common wrong turn: validating shape (depth, complexity) but never testing it. A depth limit
that was implemented but never covered by a test asserting it actually rejects an over-depth
request is a control that looks present in code review and absent in practice the first time it
matters.
Write a Python function verify_jwt(token: str, expected_aud: str, expected_iss: str, jwks_url: str) -> dict that validates a JWT. Requirements: verify signature using JWKS, reject tokens with alg 'none', validate aud/iss/exp/nbf fields, support key rotation by using kid header and caching JWKS with TTL. Pseudocode is acceptable: show the key validation and caching logic.
Sample Answer
Approach
Reject unsafe algorithms before touching any key material, look up the signing key by its kid (key ID) header against a cached JSON Web Key Set (JWKS), refresh that cache on a time-to-live (TTL) and on a cache-miss (to support rotation), then let a JWT library do the actual signature and claim verification rather than hand-rolling cryptography. This example uses the real PyJWT library so the validation logic is genuine, not pseudocode dressed up as real code.
import time
import jwt # PyJWT
class JWKSCache:
def __init__(self, jwks_url: str, ttl_seconds: int = 300):
self.jwks_url = jwks_url
self.ttl_seconds = ttl_seconds
self._keys = {}
self._fetched_at = 0.0
def _fetch(self):
# real implementation: requests.get(self.jwks_url).json()["keys"],
# indexed by each key's "kid"
self._keys = fetch_jwks_keys_by_kid(self.jwks_url)
self._fetched_at = time.time()
def get_key(self, kid: str, force_refresh: bool = False):
stale = (time.time() - self._fetched_at) > self.ttl_seconds
if force_refresh or stale or kid not in self._keys:
self._fetch()
return self._keys.get(kid)
def verify_jwt(token: str, expected_aud: str, expected_iss: str, jwks_url: str, cache: JWKSCache) -> dict:
header = jwt.get_unverified_header(token)
alg = header.get("alg", "")
if alg.lower() == "none" or not alg.startswith(("RS", "ES", "PS")):
raise jwt.InvalidTokenError(f"rejected alg: {alg!r}")
kid = header.get("kid")
if not kid:
raise jwt.InvalidTokenError("token header missing 'kid'")
key = cache.get_key(kid) or cache.get_key(kid, force_refresh=True)
if key is None:
raise jwt.InvalidTokenError(f"no matching key for kid={kid}")
return jwt.decode(
token,
key=key,
algorithms=[alg],
audience=expected_aud,
issuer=expected_iss,
options={"require": ["exp", "iat", "nbf"]},
)
Worked example
This continues directly from the JWKSCache/verify_jwt code in the Approach section above, in the same session (pip install pyjwt cryptography covers both), and was actually run immediately after that code against a real RSA-signed token and a real in-memory JWKS. It generates its own RSA key pair and stubs the JWKS HTTP fetch with a plain dict, so - combined with the code above - there is nothing left undefined:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
KID = "2026-08-key-a"
rsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_pem = rsa_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public_pem = rsa_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
def fetch_jwks_keys_by_kid(jwks_url: str) -> dict:
# Stands in for requests.get(jwks_url).json()["keys"] indexed by kid;
# here it just returns the one public key generated above.
return {KID: public_pem}
cache = JWKSCache(jwks_url="https://issuer.example.com/.well-known/jwks.json")
now = int(time.time())
claims = {
"sub": "user-4471", "aud": "orders-api", "iss": "https://issuer.example.com",
"iat": now, "nbf": now, "exp": now + 3600,
}
token = jwt.encode(claims, private_pem, algorithm="RS256", headers={"kid": KID})
print("token header:", jwt.get_unverified_header(token))
result = verify_jwt(token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
print("verified claims sub/aud/iss:", result["sub"], result["aud"], result["iss"])
Actual printed output:
token header: {'alg': 'RS256', 'kid': '2026-08-key-a', 'typ': 'JWT'}
verified claims sub/aud/iss: user-4471 orders-api https://issuer.example.com
And the two rejection paths, also actually run against the same cache:
none_token = jwt.encode(claims, None, algorithm="none")
try:
verify_jwt(none_token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
except jwt.InvalidTokenError as e:
print("alg:none correctly rejected:", e)
wrong_aud_token = jwt.encode({**claims, "aud": "wrong-api"}, private_pem, algorithm="RS256", headers={"kid": KID})
try:
verify_jwt(wrong_aud_token, "orders-api", "https://issuer.example.com", cache.jwks_url, cache)
except jwt.InvalidTokenError as e:
print("wrong audience correctly rejected:", type(e).__name__)
alg:none correctly rejected: rejected alg: 'none'
wrong audience correctly rejected: InvalidAudienceError
(The RSA key pair is generated fresh each run, so its bytes will differ if you rerun this, but the verification outcomes shown above do not depend on the specific key material and will reproduce identically.)
Key points
- Algorithm is checked and constrained before any key lookup, since accepting
alg: noneor letting the token dictate an unexpected algorithm (such as switching an RSA-verified endpoint to HMAC using the public key as the HMAC secret) is the classic algorithm-confusion attack this design has to close off first. - The
kidheader, not just the algorithm, selects which cached key to use, which is what makes key rotation possible: the issuer can publish a new key under a newkidwhile old tokens signed under the previouskidkeep validating until they naturally expire. - A cache miss on a known-valid
kidtriggers exactly one forced refresh, handling the case where the issuer just rotated and this service's cache has not caught up yet, without falling back to an unbounded retry loop.
Complexity
Aside from the underlying signature verification itself (a constant-time cryptographic operation for a fixed key size), this is O(1): one dictionary lookup for the cached key, refreshed only on TTL expiry or a genuine cache miss, never a network call on the common path.
Edge cases
An unrecognized kid should trigger exactly one forced refresh, not unbounded retries, since an attacker sending garbage kid values could otherwise force repeated JWKS fetches as a denial-of-service amplification vector. Clock skew between the issuer and this service means exp and nbf checks should allow a small leeway (PyJWT's leeway parameter) rather than failing on a difference of only a few seconds. Empty or malformed key material returned from the JWKS endpoint should fail closed, raising an error, never silently treated as "no key required."
Trade-offs & pitfalls
Pseudocode that skips the algorithm check entirely, or that checks it after fetching the key, is a real, exploitable ordering bug, not a stylistic nitpick. Caching JWKS forever (no TTL) defeats rotation; caching with no TTL and no force-refresh-on-miss defeats it just as badly, since a legitimate just-rotated key would look like a permanent cache miss.
Write a small Express middleware in Node.js that checks for a bearer token in the Authorization header, rejects requests with a 401 JSON response when missing or invalid, and logs request id and path. Provide the middleware signature and briefly describe how you'd integrate it into the request pipeline and unit-test it.
Sample Answer
A bearer-auth Express middleware uses the standard (req, res, next) signature: it extracts the Authorization header, rejects immediately with a JSON 401 body if it's missing or malformed, otherwise verifies the token and calls next(), logging the request id and path on every branch so failures are traceable without ever logging the token itself.
Approach
- Read the request id (or generate one) and the path up front, needed for logging regardless of outcome.
- Match
Authorizationagainst/^Bearer\s+(.+)$/i; a non-match means "missing or malformed", return 401 immediately without attempting token verification. - Verify the extracted token; a thrown error or falsy result means invalid, return 401.
- On success, attach the resolved identity to
req.userand callnext().
Code
// middleware/authBearer.js
const { verifyToken } = require('./tokenValidator'); // may be sync or async
function authBearer(req, res, next) {
const requestId = req.headers['x-request-id'] || 'unknown';
const path = req.originalUrl || req.url;
const header = req.headers['authorization'] || '';
const match = header.match(/^Bearer\s+(.+)$/i);
if (!match) {
console.warn(`[auth] reqId=${requestId} path=${path} result=missing_token`);
return res.status(401).json({ error: 'missing_bearer_token' });
}
const token = match[1];
Promise.resolve()
.then(() => verifyToken(token))
.then((user) => {
if (!user) {
console.warn(`[auth] reqId=${requestId} path=${path} result=invalid_token`);
return res.status(401).json({ error: 'invalid_token' });
}
req.user = user;
console.info(`[auth] reqId=${requestId} path=${path} result=ok userId=${user.id}`);
next();
})
.catch((err) => {
console.error(`[auth] reqId=${requestId} path=${path} result=validator_error message=${err.message}`);
res.status(401).json({ error: 'authentication_error' });
});
}
module.exports = authBearer;
Integration
Mount globally with app.use(authBearer) to protect every route registered after it, or per-route with app.get('/orders/:id', authBearer, handler) when only some routes need auth. Wrapping verifyToken in Promise.resolve().then(...) means the middleware works whether the underlying check is synchronous (a local JWT signature check) or asynchronous (a call to a remote auth service), without ever blocking Express's event loop.
Key points
The response body never distinguishes "missing" from "expired" from "bad signature", all three collapse to a generic 401 with a short error code, so an attacker learns nothing about which part of a forged token was wrong. Logging happens on every branch, including success, so a request id always maps to an auth decision in the logs, without the raw token ever appearing in them.
Complexity
Time is O(1) per request for the header parse and regex match; the dominant cost is whatever verifyToken does, a local signature check is roughly constant relative to token size, while a remote introspection call (asking the auth server over the network whether a token is still valid, instead of checking its signature locally) adds network latency, not algorithmic complexity. Space is O(1) beyond what Express already allocates per request.
Edge cases
A header present but not prefixed with Bearer (for example Basic ...) falls into the "missing" branch and returns 401. Duplicate Authorization headers are normalized by Node/Express to the first one (subsequent duplicates are silently discarded, not merged or overridden); if that matters for your threat model, reject the request outright instead of silently picking one. verifyToken throwing synchronously versus rejecting a promise are both caught by the same .catch, because the call is wrapped in Promise.resolve().then(...). A token that's valid but belongs to a since-disabled account can't be caught by this middleware alone, that check belongs to a separate authorization or session-revocation step downstream.
Unit testing
Using supertest and jest, with tokenValidator.verifyToken mocked: missing header returns 401 with missing_bearer_token; malformed header (Authorization: Token abc) returns 401; verifyToken resolving null returns 401 with invalid_token; verifyToken resolving a user object results in next() being called and req.user being set; verifyToken rejecting returns 401 with authentication_error, and the mocked logger's calls never contain the raw token string.
Trade-offs and pitfalls
Logging every failure at warn is useful for debugging but noisy under credential-stuffing traffic, pair it with rate limiting upstream rather than trying to fix that inside this middleware. Returning identical error codes for "missing" and "invalid" is a deliberate security trade-off (less information handed to an attacker) against debuggability (harder for a legitimate client's developer to self-diagnose); most public APIs accept that trade.
Unlock Full Question Bank
Get access to all 20 API Security, Authentication and Authorization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.