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.
Compare opaque tokens versus self-contained JWTs for service-to-service authentication in a distributed microservices environment. Discuss performance (validation latency), revocation complexity, payload confidentiality, token size, caching implications, and give recommendations for hybrid approaches that balance stateless validation with revocation needs.
Sample Answer
Direct answer
Opaque tokens trade a network round trip (an introspection call to the issuer) for instant, centralized revocation. Self-contained JSON Web Tokens (JWTs) trade that centralized control for fast, local, offline validation. In a distributed machine-to-machine (M2M) environment at real scale, most teams land on a hybrid: short-lived signed JWTs as the default, since the overwhelming majority of calls should need zero network hop to validate, backed by a narrow, fast-path mechanism for the rare "kill this credential right now" case.
Structured elaboration
| Dimension | Opaque token | Self-contained JWT |
|---|---|---|
| Validation latency | Every validating service calls the issuer's introspection endpoint, adding a network hop and making the issuer a shared, latency-sensitive dependency at scale | Local signature check only, using a cached public key, no network call, scales horizontally with the caller itself |
| Revocation | Trivial: the issuer marks the token invalid, the very next introspection call reflects it | Hard: the token is valid until its exp claim regardless of what the issuer now wants, unless you add an auxiliary mechanism |
| Payload confidentiality | The token itself carries no information; a captured token reveals nothing without querying the issuer | Claims are base64url-encoded, not encrypted, by default, readable by anyone holding the token, including any intermediary that logs or proxies it |
| Token size | Small and fixed, often just an opaque identifier | Grows with claim count, adding real header overhead on every call at high queries-per-second (QPS) if claims bloat |
| Caching implications | Services cache introspection results, reintroducing a staleness-versus-load trade-off on top of the revocation problem itself | Services cache the issuer's signing keys (via a JWKS, JSON Web Key Set, endpoint), which change rarely, so this cache is cheap and carries no correctness trade-off |
Why revocation is the real fork in the road: because a JWT is self-contained, "revoking" it does not mean anything to the token itself, the signature still verifies and the claims are still readable. Real revocation for JWTs requires bolting on state: short time-to-live (TTL) values as the default mitigation (bounding the exposure window), a deny-list checked at validation time (which reintroduces a lookup, partially undoing the statelessness benefit you adopted JWTs for), or issuer-side generation/versioning per client.
Worked example
Consider a service mesh where an order service calls an inventory service, which calls a pricing service, on every checkout request. With opaque tokens, each of those two internal hops adds a full round trip to the issuer's introspection endpoint before the call is even allowed to proceed, meaning a single external request now pays for multiple serial introspection calls stacked on top of its own logic. With signed JWTs, each hop verifies the caller's token locally against a cached public key, no extra network dependency introduced by authentication itself. This qualitative difference, not a specific millisecond figure, is why introspection-per-call does not scale cleanly as call chains get deeper.
Recommendations for a hybrid approach
- Default to short-lived signed JWTs (minutes, not hours, since machine-to-machine calls do not need a human to reauthenticate) so the common case stays local and fast.
- Pair that with a lightweight, narrow deny-list checked only for the rare case that actually needs it (a compromised service account, a discovered key leak), not on every single request; expire each deny-list entry once the underlying JWT would have expired anyway, so the extra state stays bounded rather than growing forever.
- Support issuer-side token-family versioning (bumping a minimum-issued-at cursor per client) so you can cheaply invalidate every future token for a specific caller, checked at the same low frequency as the JWKS cache refresh, without a per-request lookup.
- Reserve opaque tokens plus introspection for genuinely high-stakes, low-volume paths, such as issuing a brand-new elevated-privilege credential, where the extra round trip is an acceptable cost for tighter control.
Trade-offs & pitfalls
Choosing JWTs everywhere and ignoring the revocation gap is a common answer that sounds clean but quietly assumes a compromised credential is an acceptable risk for its full remaining lifetime. Choosing opaque tokens everywhere under-appreciates that introspection becomes the single most-called, most latency-sensitive endpoint in the whole system as call volume grows. A subtler pitfall: forgetting that JWT claims are readable, not encrypted, and putting anything genuinely secret into a claim, where it is visible to every intermediary that ever sees the token.
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.
Walk me through mutual TLS (mTLS): how does the handshake differ from standard one-way TLS, how do the client and server present and verify each other's certificates, and what are the practical options for certificate provisioning and rotation for service-to-service authentication in a microservice or service-mesh deployment?
Sample Answer
Direct answer
Mutual TLS (mTLS, where "TLS" is Transport Layer Security, the protocol that encrypts and
authenticates network connections) extends standard one-way TLS by having the client also
present a certificate that the server verifies, so both sides cryptographically prove their
identity to each other before any application data flows. In standard one-way TLS only the
server proves who it is; the client stays anonymous at the transport layer and any identity
checking happens later, in the application (a password, a bearer token).
Structured elaboration
How the handshake differs from one-way TLS. In a plain TLS handshake, the server sends its
certificate and the client verifies it against a trusted certificate authority (CA); the client
never presents one of its own. In an mTLS handshake, the server additionally sends a
CertificateRequest message, the client responds with its own certificate plus a
CertificateVerify message (a signature over the handshake transcript, proving the client
actually holds the private key matching that certificate, not just a copy of the public
certificate), and the server verifies the client's certificate against its own trusted CA
(commonly a private, internal CA for service-to-service traffic rather than a public one) before
completing the handshake. If either side's certificate fails verification, the connection is
refused before any request or response is exchanged.
What each side verifies. The client checks the server's certificate chain up to a trusted
root, the certificate's validity window, and that the certificate's subject matches the hostname
being connected to (the checks that already happen in ordinary HTTPS). The server does the
mirror image for the client: chain validity, expiry, and (this is the part unique to mTLS as an
authentication mechanism) that the certificate's identity (its Subject or a SPIFFE-style URI in
the Subject Alternative Name) matches an identity the server is willing to trust, and that the
certificate has not been revoked.
Provisioning and rotation options for service-to-service auth:
- Long-lived certificates issued manually or by a slow internal PKI (public key
infrastructure, the systems and processes for issuing and managing certificates), rotated
every 6 to 12 months. Simple to reason about but a compromised private key stays valid for a
long time, and rotation is often a manual, error-prone, outage-risking event precisely because
it happens rarely. - Short-lived certificates (hours, not months) issued automatically by an internal CA and
rotated continuously, often via a sidecar proxy that handles issuance and rotation
transparently to the application. This is the pattern service meshes like Istio or Linkerd
use, frequently paired with SPIFFE (Secure Production Identity Framework For Everyone, a
standard for representing workload identity as a URI) so identity is tied to what a workload
is (its service account, its namespace) rather than to a long-lived secret. Short TTLs shrink
the blast radius of a leaked key dramatically, since the certificate expires on its own within
hours even if revocation never fires. - A managed cloud CA or secrets-manager-backed issuance for teams that do not want to
operate their own internal CA, trading some control for less operational burden.
Worked example
sequenceDiagram
participant C as Client
participant S as Server
C->>S: ClientHello
S->>C: ServerHello plus Server Certificate
S->>C: CertificateRequest
C->>S: Client Certificate
C->>S: CertificateVerify (signed with client private key)
S->>S: Verify client cert against trusted CA, check chain and revocation
C->>S: Finished
S->>C: Finished
Note over C,S: Both sides now hold a mutually authenticated encrypted channel
The two extra round-trip messages compared to one-way TLS are CertificateRequest (the server
asking) and the client's Client Certificate plus CertificateVerify pair (the client proving
it holds the matching private key, not merely presenting a public certificate it copied from
somewhere). Everything after Finished on both sides is identical to ordinary TLS: an encrypted
channel, just one where the server now also knows, cryptographically, which specific
service-identity it is talking to, without needing an application-layer credential to establish
that.
Trade-offs and pitfalls
- mTLS proves connection identity, not user identity. It tells a server which service or
workload is calling, which is exactly the right primitive for service-to-service traffic in
a microservice or service-mesh deployment; it is the wrong tool for authenticating an
individual end user, since a human does not carry a private key the way a workload's sidecar
does. OAuth 2.0 or session-based authentication remains the right layer for user identity, and
the two are often combined (mTLS between services, a user token passed through inside that
channel). - Short-lived automated certificates need working automation, not just working crypto. If
the sidecar or agent responsible for rotation fails silently, certificates expire and every
connection using them starts failing at once, an outage that a slower manual rotation schedule
is less exposed to (at the cost of a much larger blast radius if a key leaks). Automated
rotation needs its own monitoring and alerting on issuance failures, not just on the
certificates' expiry dates. - Common wrong turn: skipping revocation checking because "the certificates are short-lived
anyway." Short TTLs reduce how long a compromise matters, but do not eliminate the window
entirely; a certificate stolen minutes before use is still valid until it expires, so
revocation checking (or, more commonly in practice, simply re-issuing all workload identities
and rotating the internal CA's trust) still matters for a confirmed compromise. - Common wrong turn: terminating mTLS at a load balancer and trusting an internal header for
identity afterward. If the load balancer is not itself inside the trust boundary you are
defending, or if an internal service can be reached directly without going through it, an
attacker who reaches the internal network can forge the identity header the same way they
would forge any other unauthenticated claim.
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're asked to architect a zero-trust setup for a hybrid environment exposing APIs to internal services, external partners, and mobile clients. Cover identity and access management, device posture checks, short-lived credentials, conditional access policies, service identity, TLS/mTLS, API gateway and enforcement points, and how to support clients in intermittent connectivity scenarios.
Sample Answer
Direct answer
A zero-trust design for a hybrid environment treats every caller, whether it is an internal
service, an external partner, or a mobile client, as untrusted by default and re-verifies
identity and context on every request, rather than granting broad access once a caller is
"inside the network." The core building blocks are strong identity for both users and services
(short-lived credentials instead of static secrets), device and context signals evaluated at
request time (conditional access), and a small number of well-defined enforcement points (an API
gateway plus per-service checks) that consistently apply policy across on-prem, multiple clouds,
and partner networks rather than each environment inventing its own rules.
Structured elaboration
Identity and access management. Every principal (human user, service, and partner
integration) needs a durable, centrally-managed identity, issued by a single identity provider
(or federated set of providers) rather than per-environment local accounts. Users authenticate
via OpenID Connect (OIDC, an identity layer built on OAuth 2.0) with the resulting token carrying
verified claims about who they are; services authenticate to each other using workload identity
(certificates or signed tokens tied to what the service is, not a shared secret it holds).
Device posture checks. For flows that originate from a device (a partner's engineer, a
mobile client), the access decision should factor in device state; whether it is managed,
patched, has disk encryption enabled, is not jailbroken/rooted, rather than trusting the network
location it is calling from. A request from a fully-patched, managed corporate laptop and one
from an unknown personal device should not receive the same default trust even if both present a
technically valid user token.
Short-lived credentials. Replace long-lived static API keys and passwords with
short-lived, automatically renewed tokens wherever the calling pattern allows it: OAuth access
tokens with lifetimes of minutes to a couple of hours, backed by refresh flows, and short-lived
certificates for service identity (paired with automated rotation, discussed further under
mTLS). A short lifetime bounds how long a leaked credential remains useful even if revocation is
delayed.
Conditional access policies. Access decisions combine identity, device posture, and context
(is this request from a location or pattern consistent with the user's history, is it during a
plausible time window, is the requested action unusually sensitive) into a policy evaluated at
request time, not just at login time; a session that started low-risk can be required to
step up (re-authenticate, add MFA) if its behavior later looks anomalous.
Service identity and enforcement points. Between services, mTLS (mutual TLS, where each side
proves its identity with a certificate) paired with a workload-identity standard like SPIFFE (Secure Production Identity Framework For Everyone, a standard for automatically issuing short-lived, verifiable identities to services)
gives every service a verifiable identity independent of network location, which matters
specifically because "hybrid" means you cannot rely on network topology (a private subnet, a VPN
tunnel) as a trust signal the way a single-cloud, single-network design sometimes does. An API
gateway sits at the edge for external and partner traffic as the primary enforcement point for
coarse-grained checks (authentication, rate limiting, gross authorization); internal
service-to-service calls enforce their own finer-grained authorization at each service, since a
single central gateway cannot see or safely encode every service's specific business rules.
Trust boundaries across on-prem, multi-cloud, and partner networks. Segment the environment
into explicit trust zones rather than assuming one flat network, and make every crossing between
zones go through an identity-checked enforcement point instead of being implicitly allowed by
network routing. For the cloud-side permissions surface specifically, CIEM (cloud infrastructure
entitlement management, tooling that inventories and right-sizes the often-sprawling permissions
granted to cloud identities and roles) is the practical mechanism for keeping the
identity-to-permission mapping from drifting into over-privilege as the environment spans
multiple cloud providers, each with its own IAM (Identity and Access Management, the system that governs who or what can access cloud resources) model; operationalize boundary changes with
automated testing (a policy change is deployed through the same CI/CD pipeline as code, with
automated checks that a proposed change does not accidentally widen an existing trust boundary)
rather than manual firewall-rule edits.
Supporting intermittent connectivity. Mobile and some partner clients cannot always reach the
identity provider or policy decision point in real time. Support this with short-lived cached
decisions (a token that remains valid, and whose validity can be checked locally via signature,
for a bounded window even if the issuer is briefly unreachable) rather than a hard requirement
that every single request round-trip to a live policy check; balance that against the same
short-lived-credential principle by keeping the cached window short enough that a revoked
credential is not usable for long after revocation.
Worked example
graph TD
C1[Internal Service] -->|mTLS plus SPIFFE identity| GW[API Gateway - PEP]
C2[External Partner] -->|OAuth token plus mTLS| GW
C3[Mobile Client] -->|short lived token plus device posture| GW
GW --> PDP[Policy Decision Point]
PDP -->|check identity, posture, context| IAM[Identity Provider]
IAM --> PDP
PDP -->|allow or deny| GW
GW --> BE[Backend Services]
The gateway is the policy enforcement point (PEP): it never decides trust on its own, it forwards
the identity and context signals it collected (which credential type, what device posture, what
network origin) to the policy decision point (PDP), which consults the identity provider and
returns an allow or deny. This separation is what lets the same enforcement logic apply
consistently whether the caller is an internal service crossing a cloud boundary, an external
partner, or a mobile client on an unreliable connection: the PEP's job (collect signals, forward,
enforce the verdict) does not change per caller type, only the specific signals available do.
Trade-offs and pitfalls
- A central policy decision point can become a latency and availability bottleneck. Cache
decisions locally at the enforcement point for a short, explicitly bounded window to absorb
brief PDP unavailability and reduce round-trip latency, rather than either making every request
block on a live PDP call or letting enforcement points make their own independent (and
potentially inconsistent) decisions. - Zero trust does not mean zero trust in the credential's assertions once verified, it means
not trusting network location as a substitute for verification; conflating the two leads teams
to over-engineer per-request re-verification for signals (like a properly-scoped, freshly-issued
short-lived token) that were already strongly verified moments earlier. - Common wrong turn: building the identity and policy layer first and treating multi-cloud
CIEM as a later cleanup task. Cloud IAM permissions sprawl quickly and independently of your
application-level zero-trust design; without CIEM-driven visibility from early on, the
"authorized" answer your policy layer gives can still be sitting on top of drastically
over-permissioned cloud roles underneath it. - Common wrong turn: applying identical policy rigor to every zone. A partner integration
handling low-sensitivity data does not need the same conditional-access strictness as an
internal service touching customer financial records; uniform maximum strictness everywhere
usually just produces friction that teams route around, rather than better security.
Unlock Full Question Bank
Get access to all 25 API Security, Authentication and Authorization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.