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.
You must securely integrate several third-party APIs into your platform. Describe a secure integration strategy covering vendor vetting, credential management (per-tenant credentials, rotation), sandboxing/testing, rate-limiting and circuit-breakers, monitoring for anomalous behavior, contractual SLAs and how to mitigate supply chain risks from third-party compromises.
Sample Answer
Direct answer
Treat every third-party API integration as an extension of your own attack surface, not a black box you can trust by contract alone. The strategy has to cover three separate failure windows: before onboarding (vendor vetting), during normal operation (isolated credentials, rate limiting, monitoring), and the day the vendor itself gets breached (supply chain containment), because all three have actually happened to real, well-known companies.
Structured elaboration
Vendor vetting
Before integrating, assess the vendor's own security posture: a SOC 2 or ISO 27001 attestation (third-party audits that certify a vendor's security controls), their breach history, how they handle your data at rest and in transit, and whether they support scoped credentials and signed webhooks on their side. Treat this the same way you would vet a subprocessor, because that is functionally what they are.
Credential management
Never share one platform-wide secret across every tenant's connection to a vendor. Issue per-tenant, or per-integration, credentials, so a leak or compromise tied to one tenant's connection does not unlock every other tenant's data through the same key. Rotate on a fixed cadence and on any signal of compromise, and make rotation an operational non-event: run old and new secrets valid in parallel for a short overlap window, so partners are never forced through a hard, scary cutover the moment a secret changes.
Sandboxing and testing
Integrate against the vendor's sandbox or test environment first. Even in production, constrain what the integration's credential and network identity are actually allowed to touch, an egress rule permitting only the vendor's documented IP ranges or domains, not open outbound traffic from that service.
Rate limiting and circuit breakers
Apply outbound rate limits so a runaway retry loop on your own side does not get you throttled or banned by the vendor. Apply inbound circuit breakers so a slow or failing vendor does not cascade into your own API's availability, since a synchronous call to a vendor that hangs can otherwise block your own request threads or connections, turning a vendor incident into your incident.
Monitoring for anomalous behavior
Baseline the normal call volume and pattern per integration, and alert on deviation in either direction: a sudden spike could mean abuse routed through your platform, a sudden drop could mean the vendor silently changed something and you are now failing calls quietly. Track the vendor's own status page and security advisories as an input too, not only your own internal metrics.
Contractual SLAs (Service Level Agreements)
Define uptime expectations, data handling terms, breach-notification timelines (how fast the vendor must tell you if they get breached), and right-to-audit terms. A security control you cannot enforce technically still needs to exist as a contractual obligation with a real consequence attached.
Mitigating supply chain risk
Assume the vendor will eventually be compromised and design so that outcome is survivable: scoped, per-tenant credentials limit blast radius (as above); no standing write access beyond what is actually needed; alerting tuned specifically to catch abnormal use of the vendor-facing credential, not just general auth logs; and a documented, actually-tested kill switch that revokes the vendor's access immediately without requiring a deploy.
Worked example
A platform integrates a third-party shipping-label API. Each tenant gets its own API key issued at onboarding, scoped to that tenant's shipments only. Outbound traffic to the vendor is restricted to their documented IP range via an egress allowlist. A circuit breaker trips if the vendor's error rate crosses a threshold, falling back to a queued retry instead of blocking checkout requests. When the vendor discloses a breach of their own systems, the response is to immediately revoke every tenant's key for that vendor from a single admin action (the kill switch), re-issue fresh keys once the vendor confirms remediation, and check the anomaly-monitoring dashboard for any tenant whose usage pattern changed in the days before the disclosure, since that is the fastest way to spot whether the compromise was already being exploited through this platform.
Trade-offs & pitfalls
Per-tenant credentials multiply operational complexity, more secrets to rotate, store, and monitor, than a single shared key. That cost is worth paying at any meaningful scale because it bounds the blast radius of a single leak, but a small startup that skips it "for now" finds it much harder to retrofit later once hundreds of tenants already share one key. Over-trusting a vendor because they are large or well-known is a real, recurring trap: some of the most damaging third-party compromises in recent memory involved exactly that kind of vendor. Circuit breakers and timeouts that are not tuned aggressively enough still let a slow vendor degrade your own service before the breaker actually trips.
You operate a mixed monolith + microservices environment. For security controls (authentication, authorization, rate limiting, input/schema validation, transport security), decide which responsibilities should be enforced at the API gateway/proxy and which should remain inside services. Justify choices with availability, security, and performance trade-offs and propose testing and observability to validate enforcement.
Sample Answer
Direct answer
Push the checks that are cheap, universal, and identity-only to the gateway (authentication verification, transport security, coarse rate limiting, structural request validation), and keep the checks that need business or ownership context inside the service (fine-grained authorization, business-aware rate limiting, semantic validation). Never treat the gateway's decision as the only check: services should still re-verify authorization even for traffic they assume already passed the gateway, because a bypass or misconfiguration at the gateway should not be the single point of failure for data access.
Structured elaboration
| Control | At the gateway | Inside the service | Why the split |
|---|---|---|---|
| Authentication | Verify token signature and expiry once, forward a verified identity to downstream services | Trust the forwarded identity, do not re-parse raw credentials | Cheap and identical for every route; centralizing it avoids every service wiring its own token validation |
| Authorization | Coarse: is this identity allowed to call this route at all | Fine-grained: does this specific caller own this specific resource | The gateway has no idea which record ID belongs to which user; that context lives only in the service |
| Rate limiting | Global/per-key throttling to protect the whole platform from volume abuse | Business-aware limiting (e.g. failed login attempts per account) that needs domain state | The gateway can count requests; it cannot reason about "too many wrong passwords for this specific account" |
| Input/schema validation | Structural: does the payload match the declared shape, reject malformed junk early | Semantic: is this SKU real, is there enough stock, do these fields make business sense together | Structural checks are cheap and universal; semantic checks require the service's own data |
| Transport security | TLS termination for client-to-gateway traffic | Mutual TLS or a service mesh for gateway-to-service and service-to-service hops | Encrypting only the outer hop leaves the internal network unauthenticated between services |
Worked example
A checkout request hits the gateway without a valid token: the gateway rejects with 401 before the order service, inventory service, or payment service ever see it, saving three services from processing traffic that was never going to be allowed. A validly authenticated request for PATCH /orders/482 is forwarded with a verified user-id header; the order service still checks that the caller actually owns order 482 before applying the patch, because the gateway only confirmed "this is a real, authenticated user," not "this user owns this specific order." If that service-side ownership check were removed on the assumption the gateway already handled it, any authenticated user could edit any order by changing the ID in the URL, which is exactly the Broken Object Level Authorization pattern, one of the most reliably tested authorization failures in API interviews at any level.
Trade-offs & pitfalls
Availability: a gateway that is horizontally scaled and stateless is not a bigger single point of failure than any other tier, but a gateway that grows to hold business logic becomes a deploy bottleneck for every service behind it, so keep it thin on purpose.
Performance: the extra hop at the gateway adds latency, but it is repaid by filtering malformed or unauthenticated traffic before it costs any downstream service compute, which is a net win under load.
Security: defense in depth means the service re-checks authorization even though the gateway already made a coarse allow decision. A common pitfall is deleting service-side authorization checks because "the gateway already checks it," which turns a misrouted internal call, a compromised adjacent service, or a gateway misconfiguration into a full authorization bypass.
Testing and observability: run contract tests that assert the gateway's allowed routes and the service's own authorization rules agree, so they cannot silently drift apart. Run synthetic BOLA probes directly against services in a staging environment, bypassing the gateway entirely, to confirm services do not rely on the gateway as their only defense. Correlate logs across the gateway and every service hop with a shared request ID, track 401/403 rates and rate-limit rejections per route as standing metrics, and alert when the gateway's allow decision and a service's deny decision disagree for the same request, since that disagreement is itself a signal of policy drift between the two layers.
You need a scalable multi-tenant authorization model for APIs that supports hierarchical roles, resource scoping, and delegation. Specify where policy evaluation should occur (gateway vs dedicated policy service), how to store and cache policies efficiently, and how to support tenant-specific custom roles without exploding policy cardinality.
Sample Answer
Put a cheap, coarse allow/deny check at the API gateway using cached, precomputed permission data, and send only the requests that need real policy logic, delegation checks, custom-role composition, attribute conditions, to a dedicated policy service (a Policy Decision Point, or PDP). Keep tenant-specific customization cheap by representing custom roles as compositions of a small, shared set of permission primitives instead of duplicating a full permission list per tenant.
Where policy evaluation should occur
The gateway is the fast path: it holds a short-TTL cached, flattened "effective permissions" record per (tenant, principal) pair and handles the common case, a simple role check, in-process with no network hop. The dedicated PDP is the slow path: it evaluates anything the gateway's cache can't answer confidently, delegation constraints, attribute-based conditions, or a freshly-changed role not yet cached, and the gateway calls it with a bounded timeout and a defined fail-closed (deny) behavior on timeout.
flowchart LR
Client --> GW[API Gateway]
GW -- cache hit: simple role check --> Allow1[Allow / Deny]
GW -- cache miss or complex rule --> PDP[Policy Decision Point]
PDP -- reads --> Store[(Policy Store: roles, compositions, delegations)]
PDP -- decision --> GW
PDP -- flattened result --> Cache[(Short-TTL Permission Cache)]
GW -. reads .-> Cache
This hybrid exists because a pure-gateway design can't express delegation or attributes without bloating every cache entry, and a pure-PDP design, calling it on every request, adds a network round trip to every single API call, unacceptable at scale.
Storing and caching policies efficiently
Canonical roles (for example viewer, editor, billing_admin) are stored once, globally, as a list of permission primitives (resource_type:action). Tenant custom roles are stored as compositions, a pointer list referencing canonical primitives and optionally other custom roles, never a duplicated full permission list per tenant. At evaluation time, or on role change, flatten a principal's effective permissions into one compact record, cache it keyed by (tenant, principal, role-version), short TTL, and invalidate it on a role or policy change event rather than waiting out the TTL.
Hierarchical roles and delegation
Model the role hierarchy as a directed graph, where a role inherits everything a role below it can do, compute effective permissions by walking the graph once and caching the flattened result, not by walking it on every request. Model delegation as a separate, time-bound, explicitly-scoped grant ("user A can act as role R on resource set S until time T"), evaluated at the PDP rather than folded into the role graph itself, so a delegation's expiry doesn't require touching the underlying role definitions.
Permissions can also be scoped to a specific resource instance, not just a resource type, for example a role that applies only to project P17 rather than to "projects" in general. Represent that as an extra attribute on the composition (which instance it applies to) rather than as a brand-new role, so instance-level resource scoping doesn't reopen the cardinality problem the compositions above were built to avoid.
Avoiding tenant-role cardinality explosion
The failure mode to avoid is storing one full permission list per (tenant, custom role) pair: at thousands of tenants, each with a handful of custom roles, that's a policy store growing linearly with tenant count times role count times permission count. Storing compositions instead grows with the number of distinct composition shapes actually in use, not with tenant count, and many tenants reuse the same handful of role archetypes even when they name their roles differently.
Worked example
Say there are 50 canonical permission primitives (orders:read, orders:write, invoices:read, and so on). A naive design storing the full list explicitly for 10,000 tenants, each with 5 custom roles, stores up to 10,000 x 5 x 50 = 2,500,000 permission rows. Storing compositions instead, where each custom role is a short list referencing on average 5 primitives or canonical roles, stores roughly 10,000 x 5 x 5 = 250,000 rows, a 10x reduction, and the number of genuinely distinct composition shapes across tenants is often far smaller still once identical compositions are deduplicated, since tenants tend to reinvent the same handful of role archetypes ("read-only support," "billing") under different names.
Trade-offs and pitfalls
Gateway-only caching is fast but can't express delegation or fine attribute conditions; PDP-only evaluation is fully expressive but adds a round trip to every request, hence the hybrid above. Caching effective permissions improves latency but introduces staleness, always pair caching with event-driven invalidation so a revoked role takes effect immediately rather than waiting out a TTL. Composition-based custom roles are compact but harder to audit at a glance than a flat list ("what can this tenant's role actually do"), so provide a "resolve and show me the flattened permission set" admin tool rather than expecting operators to read the graph by hand.
What is an API gateway, and what security responsibilities does it typically take on for the services sitting behind it?
Sample Answer
Direct answer
An API gateway is a single entry point that sits in front of a set of backend services and handles cross-cutting concerns, routing, traffic management, and security, before a request ever reaches business logic. On the security side, its main value is enforcing cheap, universal checks exactly once, instead of every individual service having to duplicate that logic.
Structured elaboration
Typical security responsibilities a gateway takes on:
- Transport security: terminating TLS (Transport Layer Security) and enforcing HTTPS-only, including a minimum supported TLS version.
- Coarse authentication: validating a token's signature and expiry, or checking an API key, before forwarding the request at all.
- Coarse authorization: confirming this identity is allowed to call this route in general, not the fine-grained "does this caller own this specific record" check, which still belongs inside the service.
- Rate limiting and throttling: protecting the whole platform from abuse or an accidental traffic spike from any single caller.
- Request validation: rejecting malformed, oversized, or wrong-content-type requests early, before they cost any downstream service compute.
- IP allow/deny lists and basic filtering: blocking known-bad sources or request patterns before they reach anything meaningful.
- Centralized audit logging: one place to see every request that entered the system, useful for both security review and debugging.
- Identity propagation: injecting a verified identity (for example, a user-id header) into the forwarded request, so downstream services trust the gateway's verification rather than each re-parsing raw tokens themselves.
Worked example
A POST /orders request arrives with no authentication token. The gateway rejects it with a 401 response before the orders service, inventory service, or payment service ever see it, so none of them spend any compute on traffic that was never going to be allowed. A validly authenticated request for the same endpoint is forwarded along with an X-User-Id header the gateway added after verifying the token, so the orders service can trust that identity without re-validating the raw token itself.
Trade-offs & pitfalls
A gateway should take on responsibilities that are universal and cheap to check without business context, not fine-grained, per-resource authorization, which needs domain knowledge only the service actually has. The most common pitfall is treating the gateway as the only layer of defense: it is a first filter that removes obviously bad traffic early, not a substitute for a service independently checking that a specific caller is allowed to touch a specific resource.
Propose detection and mitigation strategies for abusive API usage and credential theft at scale. Cover techniques such as per-key behavioral baselines, anomaly detection, per-key throttling and freezing, ephemeral credential issuance, credential rotation, fingerprinting, and forensics-ready logging while balancing privacy and performance.
Sample Answer
Build a per-key behavioral baseline, normal request rate, endpoints touched, geography, for every API key, score each new burst of activity against its own history rather than a single global threshold, and respond with graduated actions, soft throttle, then freeze, then full revoke, so a false positive costs a legitimate client a slowdown, not a hard outage.
Per-key behavioral baselines
Track, per key, over a rolling window (for example, 7 days): request rate, endpoint mix, typical payload size, source IP or geography, and time-of-day pattern. Use a decaying window, weighting recent activity more, so a key's baseline adapts as legitimate usage genuinely changes, without being so reactive that an attacker can slowly retrain the baseline toward their own behavior, cap how fast the baseline itself is allowed to shift per day.
Anomaly detection
Combine simple rules, an absolute rate ceiling, or a geographically impossible gap between two consecutive requests, with a statistical or machine-learning layer, unsupervised outlier detection (flagging unusual activity by comparing it to the shape of normal data, with no need for pre-labeled examples of "bad") over the same behavioral features, so you catch both obvious abuse and subtler drift. Score risk as a combination of signals rather than one metric alone, as shown in the worked example below.
Per-key throttling and freezing
Use a graduated response: soft throttle (a reduced rate limit) at a moderate anomaly score, freeze (block new requests, let existing sessions time out) at a high score, and full revoke only after freeze plus either automated corroboration or human review, so a single noisy signal doesn't take down a legitimate integration outright.
Ephemeral credential issuance and rotation
For high-privilege operations, issue short-lived, single-purpose credentials, minutes rather than months, rather than relying solely on the long-lived key. Rotate long-lived keys on a fixed cadence automatically, with a grace overlap so rotation itself never causes an outage.
Fingerprinting
Collect signals that aren't tied to a person's identity. A TLS client fingerprint is the common starting point, since it's cheap to capture at the TLS layer with no application changes; an HTTP header ordering fingerprint and a hashed device signal are rarer, higher-effort additions worth reaching for only once TLS fingerprinting alone isn't separating attackers from genuine clients. The goal is to distinguish "the same script hitting us from many rotated IPs" from genuinely independent clients, without needing to know who the human behind it is.
Forensics-ready logging, balancing privacy and performance
Keep an append-only, tamper-evident log of every mitigation decision, the score, the signals that fired, the action taken, so an incident can be reconstructed after the fact. Store raw request bodies only when a risk threshold is crossed, sampled or fully captured once triggered rather than captured for every request by default, so both storage cost and privacy exposure scale with actual risk.
Worked example
Key partner-key-77 has a 7-day baseline of 150 requests/hour, 95% from a stable IP range, touching a consistent mix of 4 endpoints. In one hour it makes 900 requests (6 times baseline), from a new IP range, hitting a 5th endpoint it has never called before. Define a risk score:
score = rate_ratio + new_ip_flag + new_endpoint_flag
rate_ratio = 900 / 150 = 6
new_ip_flag = 2 (a range never seen before)
new_endpoint_flag = 1 (one never-seen endpoint)
score = 6 + 2 + 1 = 9
Thresholds: score >= 4 triggers a soft throttle (halve this key's rate limit); score >= 8 triggers a freeze (block new requests, page security on-call); score >= 15 triggers auto-revoke pending review. At a score of 9, the key is frozen and a human is paged, but not auto-revoked, since a new endpoint plus an IP change could still reflect a legitimate deployment change on the partner's side. The human reviewer's job is to distinguish that from theft within the freeze window before deciding whether to restore or revoke.
Trade-offs and pitfalls
Graduated response reduces false-positive damage but adds an operational cost, someone has to staff the review queue between freeze and revoke, size that team for your expected alert volume before relying on it. Behavioral baselines that adapt too quickly can be gamed by an attacker who ramps up slowly, capping the daily rate of baseline drift bounds this risk. Full-fidelity request logging aids forensics but raises both storage cost and privacy exposure if applied to every request, trigger deeper capture only once risk crosses a threshold, and document the retention window for that captured data separately from normal logs.
Unlock Full Question Bank
Get access to all 24 API Security, Authentication and Authorization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.