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.
Lay out the authentication and authorization model for internal data APIs that must enforce fine-grained access controls per dataset, integrate with corporate SSO, audit all accesses, and support service-to-service auth with rotating credentials. Discuss token lifetimes, caching auth decisions, centralized policy engines (OPA), and audit log design for compliance.
Sample Answer
Authenticate humans through corporate single sign-on (SSO, one login your company already manages, federated into this system) and authenticate services through short-lived, auto-rotated credentials, but make the actual per-dataset access decision in one centralized policy engine, Open Policy Agent (OPA), so "which datasets can this caller see" has a single, auditable source of truth instead of being scattered across each service's own code.
Authentication
Users authenticate via SSO using OpenID Connect (OIDC, an identity layer on top of OAuth 2.0), issuing short-lived ID tokens. Service-to-service calls authenticate with short-lived, rotating credentials, either mutual TLS certificates issued by an internal certificate authority (following the SPIFFE/SPIRE pattern (an open standard for automatically issuing and rotating short-lived, verifiable service identities, so services get a strongly-verified identity without a team hand-managing individual certificates)) or signed JWTs from an internal token service, rotated automatically on the order of hours, not months.
Fine-grained access control per dataset
Centralize the actual decision in OPA (a general-purpose policy engine) acting as the Policy Decision Point (PDP): policies reference dataset metadata from a data catalog (owner, sensitivity classification, allowed purposes) plus the caller's identity and role. Enforce the decision at a Policy Enforcement Point (PEP) embedded in each data service, applying row or column filters, or an outright deny, before data leaves the service boundary, not after.
Token lifetimes
User ID tokens are short-lived, around 15 minutes, with revocable refresh tokens and back-channel logout, so ending a corporate SSO session actually ends access to this system too. Service credentials are short-lived, 1-4 hours, scoped narrowly, and auto-rotated.
Caching auth decisions
Cache PDP decisions at the PEP with a short TTL keyed on (principal, resource, action, policy-version), and invalidate on any policy or role change via an event, not by waiting out the TTL, since a stale allow cached past a revoked grant is a real access-control gap, not just a performance quirk. For the most sensitive datasets, skip the cache entirely, calling the PDP fresh every time, and accept the added latency as the price of a policy that can never be stale.
Audit log design for compliance
Every access emits one structured, immutable event: timestamp, principal, dataset or table (with any row/column filter applied), decision, the policy version used, and the count of rows actually returned. Storing the policy version alongside the decision lets an auditor later reconstruct exactly which rule allowed a given access, even after the policy has since changed. Stream events to an append-only store, object storage with a write lock or an equivalent immutable log, separate from the systems being audited.
Worked example
An analyst with role regional_analyst (EU) queries a dataset containing customer records across regions. The catalog marks the dataset's region column as a policy input. The OPA policy reads: allow if input.action == "read" and input.subject.region == input.resource.region. The analyst's SSO-issued token carries region: EU. Their query would naturally return rows for every region; the PEP, holding the PDP's decision, pushes a row filter WHERE region = 'EU' into the underlying query engine before execution, so the analyst never receives non-EU rows in the first place, rather than receiving them and being trusted not to look. The audit log for this access records the principal, dataset id, filter applied, policy version, and row count returned, for example 42,000 rows, enough for an auditor to later confirm the filter was actually enforced, not just intended.
Trade-offs and pitfalls
Centralizing every decision in OPA is auditable and consistent, but it makes OPA's availability a shared dependency for every data service, run it as a horizontally-scaled, stateless fleet with local caching so it doesn't become a single point of failure. Caching auth decisions cuts latency for high-throughput analytics workloads but is the most common place this design quietly breaks: a revoked grant that's still honored because the cache hasn't expired yet is a real incident, not just staleness, treat cache invalidation as a security control, not a performance nicety. Pushing filters into the query engine (predicate pushdown) scales well but requires trusting that engine to actually enforce the filter it's given, validate that trust with periodic tests that attempt, and expect to fail, an out-of-scope query.
You need to implement rate-limited, audited access to an internal model endpoint for external contractors. Specify the OAuth flow, token scopes, per-call logging, and how you would detect suspicious use patterns that might indicate data exfiltration.
Sample Answer
Give each contractor a registered OAuth 2.0 client using the Client Credentials grant (a machine-to-machine flow with no interactive user) scoped down to exactly the model-inference action, with a short token lifetime, log every call with enough metadata to reconstruct who asked what without storing the full prompt or response by default, and detect exfiltration from a small set of per-client behavioral features moving together, rather than one hard threshold.
OAuth flow and token scopes
The Client Credentials grant lets the contractor's service authenticate directly with a client_id and client_secret (or, better, a mutual TLS client certificate) against the token endpoint, no human redirect is needed since there's no end user delegating access. Access tokens are short-lived JSON Web Tokens (JWTs), around 10 minutes, scoped to exactly what's needed, for example model.infer:readonly. No broader scope is granted by default; a higher-quota scope like batch inference requires a separate approval step.
Per-call logging
Log, per request: timestamp, request id, client id, org id, token id (jti, a unique id embedded in the token itself, so you can trace one specific token's activity even after it's expired), scope used, endpoint, a hash of the input rather than the raw input, input size, output size, latency, and model version. Storing the hash lets you later prove "this exact input was sent" without keeping sensitive content in plaintext logs; keep a separate, encrypted, access-controlled store of raw payloads for forensic replay only if an investigation actually needs it.
Detecting suspicious use or exfiltration
Rather than a single static threshold, compute a small set of per-client features over a rolling window and flag when several move together:
- request rate relative to that client's own multi-day rolling baseline, not a global threshold, since normal usage varies a lot by contractor
- output size distribution, a client whose average output size triples in a day is a stronger signal than one whose absolute output size is merely large
- query diversity, low diversity paired with high output volume looks like someone stitching together a large extraction across many near-identical calls
- unusual access time or source location relative to that client's own history
Worked example
Contractor client acme-ml-01 has a 7-day rolling baseline of 200 requests/day, average output 1.2 KB, from one known IP range. On day 8 the same client makes 1,800 requests (9 times baseline) with average output 3.6 KB (3 times baseline) from a new IP range. Define a simple combined risk score:
score = (requests_today / baseline_requests)
+ (avg_output_today / baseline_output)
+ (2 if new_ip_range else 0)
Plugging in the numbers: (1800 / 200) + (3.6 / 1.2) + 2 = 9 + 3 + 2 = 14. If the alert threshold is score >= 5, this client trips it by a wide margin, triggering automatic throttling to a lower rate limit plus a page to security on-call, rather than an immediate full revoke: a single feature spike alone (say, a legitimate batch job) shouldn't hard-block a contractor on its own, it's the compound score crossing the line that justifies notifying or throttling.
Trade-offs and pitfalls
Storing only a hash of the input by default protects privacy and reduces breach blast radius, but means you can't inspect the actual content during an investigation unless you've also kept a separate encrypted raw store, plan for both from day one rather than adding the raw store only after an incident. A single static rate threshold either misses low-and-slow exfiltration (many requests just under the limit, spread over days) or generates alert fatigue for bursty but legitimate contractors; per-client relative baselines fix the first problem, but need a full baseline window of history before they're trustworthy for a brand-new contractor. Auto-revoking on the first alert protects data but can wrongly cut off a contractor mid-task on a false positive, a graduated response (throttle, then human review, then revoke) balances the two.
Propose a policy and system to rotate and revoke long-lived API keys across 10,000 services and 1,000,000 keys with minimal client disruption. Describe centralized vs decentralized rotation, key versioning in the backend, publish/subscribe propagation of revocations, client notification strategies, and emergency revocation mechanisms.
Sample Answer
At this scale, rotation and revocation need two separate paths. A slow, scheduled, centrally-governed rotation path spreads renewal load evenly so no client hits a re-provisioning cliff, and a fast, decentralized emergency-revocation path propagates a deny-list to every enforcement point in well under a minute, independent of the normal rotation cadence.
Architecture
- Central Key Management Service (KMS) / policy plane: owns key metadata, versioning, audit trail, and issues new key versions.
- Publish/subscribe event bus (a durable, replicated event log such as Kafka): carries
KEY_CREATED,KEY_DEPRECATED, andKEY_REVOKEDevents. - Distributed enforcement: API gateways or sidecars at each of the 10,000 services keep a locally-cached deny-list refreshed via the event bus, so the request hot path never makes a synchronous call to the central KMS.
flowchart LR
KMS[Central Key Management Service] -- publishes --> Bus[(Pub/Sub Event Bus)]
Bus -- KEY_REVOKED event --> GW1[Gateway A]
Bus -- KEY_REVOKED event --> GW2[Gateway B]
GW1 -- local deny-list lookup --> SvcA[Services Group A]
GW2 -- local deny-list lookup --> SvcB[Services Group B]
GW1 -. periodic reconciliation poll .-> KMS
Key versioning
Every logical key has immutable versions, key_id:v1, key_id:v2, and so on. Metadata tracks status (ACTIVE, DEPRECATED, REVOKED), creation time, and a grace-period expiry. Rotation creates vN+1 as ACTIVE, marks vN DEPRECATED with an overlap window, then flips vN to REVOKED once that window closes.
Centralized vs decentralized rotation
Central, scheduled rotation is predictable and easy to audit, but the control plane must stay highly available at this scale. Decentralized, delegated rotation, where a service requests its own rotation via a signed delegation token, reacts faster to local conditions but needs strict policy bounds so a compromised service can't mint arbitrary keys. In practice, a hybrid works best: a central schedule for routine rotation, plus delegation tokens for services that need to self-rotate within policy limits.
Propagation
Each event carries key_id, new_version, action, a sequence_number, and a signature, so gateways can apply updates idempotently and reject replayed or spoofed events. Because pub/sub delivery is only "eventually" reliable in practice, a periodic reconciliation poll against the central store (for example, every 30 seconds) acts as a safety net for any gateway that missed an event.
Client notification
Passive: SDKs read the active and previous key version at startup and accept both during the grace window. Active: a webhook or push notification to registered service owners at rotation time, and again shortly before the grace window closes. Fallback: sidecars poll the KMS on a backoff schedule if their event-bus connection drops.
Emergency revocation
An admin or automated detector triggers a REVOKE, published on a high-priority channel ahead of routine rotation traffic. Gateways apply it to their local deny-list immediately on receipt, a hash-set or Bloom filter lookup (a compact, probabilistic structure that can quickly say "definitely not revoked" or "maybe revoked," trading a small false-positive rate for speed and low memory), so no round trip is added to the request path. Any client not currently connected to the bus is still caught by the periodic reconciliation poll, which bounds the worst-case exposure window to the poll interval rather than to the routine rotation cadence.
Worked example
Fleet size: 1,000,000 keys across 10,000 services, an average of 100 keys per service. Under a 90-day max-age rotation policy, spreading rotations evenly means rotating 1,000,000 / 90 ≈ 11,112 keys per day, avoiding the rotation storm a naive "rotate everything on day 90" policy would cause. The grace window is 72 hours, so a service that only reads its key at deploy time still has three days to pick up the new version before the old one is revoked. On the emergency path, if the reconciliation poll runs every 30 seconds, the worst-case time from "revoke pressed" to "rejected at every one of the 10,000 gateways" is bounded by that 30-second interval, completely independent of the 72-hour grace window used for routine rotation.
Trade-offs and pitfalls
Rotating too aggressively burns client engineering time on re-provisioning; too rarely widens the compromise blast radius, the 90-day and 72-hour figures above are a starting policy to tune against your own data sensitivity, not a fixed rule. A fully centralized design is simple to audit but makes the KMS a single point of failure at 1,000,000-key scale, hence the pub/sub fan-out to cached edge deny-lists instead of a synchronous per-request call. Bloom filters give O(1) local revocation checks with a tunable false-positive rate, but that rate must be sized (or backed by a periodic exact-set refresh) so it never wrongly allows a revoked key, only, at worst, wrongly flags a small number of valid ones for a slower fallback check. A common wrong turn is relying on pub/sub alone with no polling backstop, a single dropped message then leaves a revoked key valid indefinitely at that node.
You're building a secure webhook receiver for third-party partners. Requirements: authenticate payloads, prevent replay attacks, support retries while ensuring idempotency, scale to high volume, and allow secret rotation. Describe signing schemes (HMAC vs asymmetric), replay defenses (timestamps, unique IDs), idempotency handling and operational patterns for secret rotation.
Sample Answer
Direct answer
Sign every webhook payload so the receiver can prove it really came from the partner (a shared-secret HMAC, or an asymmetric signature if there is no shared secret), bind a timestamp and a unique event ID into that signature so a captured request cannot be replayed later or against a different event, and record processed event IDs so retried deliveries are absorbed as no-ops instead of double-processed. Handle secret rotation by accepting two valid secrets during a short overlap window instead of a hard cutover.
Structured elaboration
Signing schemes: HMAC vs asymmetric
- HMAC (Hash-based Message Authentication Code) is the common default: both sides share one secret, the sender computes a keyed hash (typically HMAC-SHA256) over the request, and the receiver recomputes the same hash and compares it. Fast, simple, and what most webhook providers (Stripe, GitHub) use.
- Asymmetric signing (the sender signs with a private key, the receiver verifies with the sender's public key) removes the need to ever share a secret at all, which matters when you cannot trust a channel to distribute a shared secret safely, or when many receivers need to verify the same sender's signature without each holding a copy of a secret that could leak. It costs more CPU per verification and adds public key distribution/rotation as its own problem.
Replay defenses
- A timestamp header, signed as part of the payload (not sent alongside unsigned), so an attacker who captures a valid request cannot replay it after altering the timestamp without invalidating the signature.
- The receiver rejects any request whose timestamp is outside a short tolerance window (a few minutes), which bounds how long a captured request stays useful even if replayed unmodified.
- A unique event ID per webhook delivery, checked against a short-lived dedup store (a cache keyed by event ID with a TTL slightly longer than the timestamp tolerance), so an identical request replayed within the tolerance window is still caught.
Idempotency for retries
- Partners retry on timeout or a 5xx response, which means the receiver will see the same event ID more than once by design, not by attack. The fix is the same dedup store used for replay defense: before doing any side effect, check whether this event ID has already been processed; if so, return success without repeating the work.
- The "already processed" check and the "mark as processed" write need to be atomic (a unique constraint in the datastore, or an atomic check-and-set in the cache) so two near-simultaneous deliveries of the same event cannot both pass the check before either marks it done.
- Respond fast: verify signature, check the dedup store, enqueue the actual business work, and return 200 immediately. Doing the real processing synchronously inside the request is what makes retries expensive and dedup races more likely under high volume.
Secret rotation
- Never a hard cutover. Accept signatures computed with either the current secret or the previous secret for a defined overlap window, and include a key identifier in the request headers so the receiver knows which secret to try first instead of testing both on every request.
- Communicate the rotation window to partners, retire the old secret only after the window closes, and treat "a partner is still signing with the retired secret past the deadline" as an operational alert, not a silent failure.
Worked example
A concrete HMAC-SHA256 signature, computed and verified exactly as shown (copy, run, and you will get the same digest since every input is pinned):
import hmac, hashlib
secret = b"whsec_5f8a3c9e2b7d4a1f6e0c8b2d9a4f7c1e"
timestamp = "1735689600"
body = b'{"event":"payment.succeeded","id":"evt_8f2a","amount":4999}'
signed_payload = timestamp.encode() + b"." + body
signature = hmac.new(secret, signed_payload, hashlib.sha256).hexdigest()
print(signature)
Output:
2e702838565a081c906544b3c8d22f6ce61ab8cedeb9babb9f7ae1245e596b14
On the receiving side, verification recomputes the same digest and compares in constant time, then applies the replay and idempotency checks:
def verify_and_should_process(headers, body, secret, seen_event_ids, now, tolerance_s=300):
timestamp = headers["X-Timestamp"]
if abs(now - int(timestamp)) > tolerance_s:
return False, "timestamp outside tolerance"
expected = hmac.new(secret, (timestamp + ".").encode() + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, headers["X-Signature"]):
return False, "bad signature"
event_id = headers["X-Event-Id"]
if event_id in seen_event_ids:
return True, "already processed, ack without reprocessing"
seen_event_ids.add(event_id)
return True, "process"
This is not run in this answer since it depends on request-time state (now, a shared dedup store); the HMAC computation above is the part with fully pinned inputs and a verifiable output.
Trade-offs & pitfalls
Using a plain string comparison (==) instead of a constant-time comparison (hmac.compare_digest) leaks timing information an attacker can use to guess the signature byte by byte. Trusting a client-supplied timestamp that is not itself signed into the HMAC input lets an attacker pair an old, still-valid signature with a fresh timestamp. If the idempotency store is local to one server instance instead of shared, two receiver replicas behind a load balancer can each independently "not have seen" the same event and both process it. Rotating a secret without an overlap window causes a hard outage for every in-flight or slightly-delayed delivery signed with the old secret.
Explain the differences between input validation, schema/contract validation (OpenAPI/JSON Schema), and output encoding. Give concrete examples of how each prevents different attack classes such as SQL injection, XSS, and parameter pollution, and list common developer mistakes that lead to validation bypasses.
Sample Answer
Direct answer
Input validation checks that a value is well-formed for the field it fills (a phone number
looks like a phone number); schema or contract validation (commonly using OpenAPI, a
specification format for describing an API's shape, or JSON Schema, a specification for
describing the structure of JSON data) checks that an entire request or response matches the
API's declared shape (required fields present, correct types, no unexpected extra fields); output
encoding transforms data on the way out so that a value which is safe as data cannot be
reinterpreted as code by whatever consumes the output (a browser rendering HTML, a database
executing a query). They are complementary layers, not substitutes for each other, and each
blocks a different attack class.
Structured elaboration
Input validation. Confirms an individual value conforms to expected format, range, and type
before it is used: a string that should be an email address actually looks like one, a quantity
field is a positive integer, a date is a real calendar date. This is the first line of defense
against malformed or unexpected data reaching business logic, but on its own it does not
guarantee an entire request is well-formed (a required field could simply be missing) or that
data is safe wherever it eventually ends up being used.
Schema and contract validation. Validates the request or response as a whole against a
formal contract: every required field present, every field the correct type, no unrecognized
fields silently accepted. Enforcing this at the API boundary (often automatically, since an
OpenAPI or JSON Schema definition can generate a validator) catches an entire category of bug
before it reaches handler code at all, and it directly prevents mass assignment style problems,
where an unexpected extra field in a request body ("isAdmin": true tacked onto a normal
profile-update payload) gets silently accepted and bound onto an internal object because nothing
rejected the unexpected field in the first place.
Output encoding. Transforms data based on where it is being written to, so that untrusted
data embedded in an output cannot be reinterpreted as a command by whatever parses that output.
The same string needs different encoding depending on its destination: HTML-encoding before
writing into an HTML page (so <script> in a stored value renders as visible text, not as an
executed tag), parameterization (not encoding) before using a value in a SQL query, so the
database engine never treats the value as part of the query's syntax.
How each prevents a different attack class:
- SQL injection is fundamentally an output-encoding problem, even though it is often
discussed as if it were an input-validation problem: a value that passes every reasonable
input-validation rule (a legitimate-looking last name likeO'Brien) can still break a
hand-built SQL string if it is concatenated directly into the query rather than passed as a
parameter. Parameterized queries (or an ORM that parameterizes for you) are the actual fix,
since they keep the value as data and never let it become part of the query's syntax,
regardless of what characters it contains. - Cross-site scripting (XSS) is an output-encoding problem specifically for the HTML/JS
context: a stored value that was correctly input-validated as "a non-empty string under 500
characters" can still contain<script>alert(1)</script>, and only encoding at render time
(or a strict content-security policy as defense in depth) stops that string from executing as
code when rendered in a browser. - Parameter pollution (sending the same parameter name multiple times, or in an unexpected
location, to see which value a poorly-specified handler actually uses) is primarily a
schema/contract validation problem: a strict schema that specifies exactly one value is
expected per field, and rejects a request that violates that shape, closes the ambiguity that
parameter pollution exploits.
Common developer mistakes that lead to validation bypasses:
- Validating on the client side only (in JavaScript in a browser, for example) and trusting that
client-side check server-side; any client-side validation is a request the server never sees
if the caller bypasses the browser entirely. - Validating a nested or optional field's presence but not revalidating its contents once it
is inside a larger, already-validated object. - Doing input validation and then building output by string concatenation anyway (
f"SELECT * FROM users WHERE name = '{name}'"), which discards everything input validation bought you the
moment it hits the output boundary, since input validation was never the layer responsible for
safe output construction in the first place. - Allowlisting only some fields in a schema (
additionalProperties: truein JSON Schema, or the
API framework's default of silently accepting unknown fields) rather than explicitly rejecting
unrecognized fields, which reopens the mass-assignment gap schema validation is supposed to
close.
Worked example
A profile-update endpoint expects {"displayName": string, "bio": string}. An attacker sends
{"displayName": "Jane", "bio": "hi", "isAdmin": true}.
- Input validation alone (checking
displayNameandbioare non-empty strings under some
length) says nothing about theisAdminfield, since input validation as commonly implemented
checks the fields it knows about, not the absence of fields it does not. - Schema validation with
additionalProperties: falserejects the whole request outright,
becauseisAdminis not a field the schema declares, closing the mass-assignment path before
it ever reaches the handler. - Separately, if
displayNameis later rendered on a public profile page as
<h1>{displayName}</h1>with no output encoding, an attacker who sets
displayName = "<img src=x onerror=alert(1)>"(a value that legitimately passes "non-empty
string under some length") gets that payload executed in every visitor's browser; only
HTML-encoding at render time (or an equivalent templating engine that encodes by default)
closes that specific gap, and it closes it regardless of what input validation rule was or was
not applied at write time.
Trade-offs and pitfalls
- These three layers fail independently, so skipping any one leaves a real gap, not a
redundant one: a request can pass schema validation perfectly (every field the right shape)
and still carry a payload that is dangerous purely because of where it later gets rendered or
interpreted, which is exactly why output encoding cannot be replaced by "we already validated
the input." - Overly strict schema validation has a real cost. Rejecting anything not explicitly listed
in the schema (additionalProperties: false) is the right default for security, but it also
means any new field a client starts sending, even a harmless one, breaks until the schema is
updated; this is a deliberate trade of forward-compatibility for safety, worth stating rather
than treating as a free win. - Common wrong turn: encoding once, at input time, and trusting it downstream. Encoding for
the wrong destination (or encoding too early, before the value passes through another layer
that expects raw data) is a frequent source of both broken functionality and residual
vulnerability; encode as close as possible to the point of output, for the destination that
specific output is going to.
Unlock Full Question Bank
Get access to all API Security, Authentication and Authorization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.