Security

Advanced API Security: Implementing Zero Trust Architecture

How to apply zero trust to an API: verify every caller, authorize each request against the resource, encrypt internal traffic and log every decision.

By the APIStack team··Updated ·9 min read

A person holding a payment card while typing on a laptop

Zero trust is a way of designing access control in which no request is trusted because of where it comes from. A call from inside the private network is checked as carefully as one from the internet. This article explains what that means for an HTTP API in practice: how callers are authenticated, how each request is authorized, how traffic is encrypted, and what has to be logged.

It is written for developers who already run an API behind some form of authentication and want to remove the places where the system still relies on network position.

What zero trust means for an API

The reference definition is NIST SP 800-207, Zero Trust Architecture. Reduced to what an API team has to act on, it makes three demands.

The first is that network location grants nothing. A service that accepts any request arriving from the cluster's address range, or from behind the gateway, has a perimeter model: one compromised pod or one server-side request forgery bug gives an attacker everything inside. Under zero trust the internal service authenticates its callers too.

The second is that access is decided per request. A valid session or token proves who the caller is, not that this caller may perform this action on this object. The decision is made each time, using the identity, the action, the resource and any relevant context.

The third is least privilege. Credentials carry the narrowest scope that lets the caller do its job and they expire quickly, so that a leaked credential is worth little.

Authenticate every caller

An API has two kinds of caller, and they authenticate differently.

End users are authenticated by an identity provider, not by the API. Multi-factor authentication, passkeys and biometric unlock all happen there, during sign-in. The API never sees a fingerprint or a one-time code; it receives an access token that the provider issued after those checks passed, and its job is to validate that token properly. If a sensitive operation needs a recent or stronger sign-in, the API can require it by checking the token's auth_time, acr or amr claims and rejecting tokens that do not meet the bar.

Validating a JSON Web Token means checking the signature against the issuer's published keys, pinning the accepted algorithm, and checking the issuer, audience and expiry. Skipping the audience check is a common mistake: it lets a token issued for a different API be replayed against yours. The example below does all of this with the jose library as Express middleware.

JavaScript
import { createRemoteJWKSet, jwtVerify } from 'jose'

const jwks = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'))

export async function authenticate(req, res, next) {
  const [scheme, token] = (req.get('authorization') || '').split(' ')
  if (scheme !== 'Bearer' || !token) {
    return res.status(401).json({ error: 'Missing bearer token' })
  }
  try {
    const { payload } = await jwtVerify(token, jwks, {
      issuer: 'https://auth.example.com/',
      audience: 'https://api.example.com',
      algorithms: ['RS256'],
    })
    req.user = {
      id: payload.sub,
      tenant: payload.tenant,
      scopes: (payload.scope || '').split(' '),
    }
    next()
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' })
  }
}

Keep access tokens short-lived, in the range of minutes, and use refresh tokens to obtain new ones. A signed token cannot be revoked before it expires unless every service checks a revocation list, so the lifetime is the revocation window. RFC 8725 lists the other JWT pitfalls worth checking against.

Services are the second kind of caller. Inside a zero trust system each workload has its own identity, and the usual way to prove it is mutual TLS: both sides present a certificate, and the server learns which service is calling from the client certificate. A service mesh such as Istio or Linkerd issues and rotates these certificates automatically; SPIFFE defines the identity format most of them use. Where a service acts on behalf of a user, pass the user's identity along as a token the receiving service validates itself, not as a plain header it has to take on trust.

API keys identify an application, not a person, and they are long-lived bearer secrets, so treat them as the weakest of these options. Store them in a secret manager, never in client-side code or a repository, give each consumer its own key so one can be revoked without affecting the others, and rotate on a schedule you have automated as well as immediately after any suspected exposure. The same applies to keys you hold for third-party APIs: a key sent in an x-api-key header to a hosted service such as APIStack belongs on your server, not in a browser bundle.

Authorize each request

Authentication answers who is calling. Authorization answers whether this caller may do this to this object, and it is where most real API breaches occur: broken object level authorization is the first entry in the OWASP API Security Top 10. The typical bug is an endpoint such as /v1/invoices/:id that checks the caller is signed in but not that the invoice belongs to them.

The fix is to make the decision with the resource in hand, deny by default, and keep the rules in one place. The middleware below loads the resource, asks a policy function for a decision and records the outcome. If the policy check throws, the request is denied.

JavaScript
export function authorize(action, loadResource) {
  return async (req, res, next) => {
    const input = { subject: req.user, action, resource: null }
    let allowed = false
    try {
      input.resource = await loadResource(req)
      allowed = input.resource !== null && (await policy.allows(input))
    } catch (err) {
      console.error('policy evaluation failed', err)
    }
    audit.record({
      subject: req.user.id,
      action,
      resource: req.originalUrl,
      allowed,
      ip: req.ip,
      at: new Date().toISOString(),
    })
    if (!allowed) return res.status(403).json({ error: 'Forbidden' })
    req.resource = input.resource
    next()
  }
}

app.get(
  '/v1/invoices/:id',
  authenticate,
  authorize('invoice:read', (req) => invoices.findById(req.params.id)),
  (req, res) => res.json(req.resource)
)

Here policy.allows can be a plain function that compares subject.tenant with resource.tenant and checks a scope. As rules multiply, moving them into a policy engine such as Open Policy Agent keeps them out of handler code and lets them be tested and reviewed on their own. Either way the policy receives attributes of the subject, the action and the resource, which is more expressive than a role check alone.

Context such as IP address or user agent can inform a decision, for example by requiring a fresh sign-in when a request arrives from an unfamiliar network, but both are easy to change and should not be the only thing standing between a caller and the data.

Encrypt traffic and stored data

Zero trust assumes the network is hostile, so traffic between internal services is encrypted as well as traffic from the internet. Terminating TLS at the load balancer and sending plain HTTP behind it does not meet that bar.

Use TLS 1.3 where both ends support it and allow TLS 1.2 as the minimum. TLS 1.0 and 1.1 are formally deprecated by RFC 8996 and should be disabled. Every TLS 1.3 cipher suite provides forward secrecy; with TLS 1.2, restrict the configuration to ECDHE suites to get the same property.

Certificate pinning is often listed as a requirement, but it has a real cost. A client that pins a specific certificate stops working when that certificate is rotated, and a mobile app with a stale pin cannot be fixed without an update. Pin only when you control both ends, pin to a certificate authority or a set of keys that includes a backup, and have a tested rotation procedure. For service-to-service traffic, mutual TLS with a private certificate authority already gives each side a narrow set of trusted issuers.

For data at rest, use the encryption your database or storage service provides, with keys held in a key management service so that access to the keys is itself authenticated, authorized and logged. Encrypt especially sensitive fields at the application level as well, so that a database credential alone does not expose them. Plan key rotation from the start: envelope encryption, where a master key wraps per-record or per-tenant data keys, makes rotation practical because only the data keys need re-wrapping.

Log decisions and watch for misuse

Verification on every request produces a record of every decision, and that record is the main tool for detecting a compromised credential. For each request, log the authenticated identity, the action, the resource, whether it was allowed and a request ID that ties the entry to logs in other services. Do not log tokens, API keys or request bodies containing personal data.

The signals worth alerting on are mostly about change: a rise in 401 or 403 responses for one credential, a caller walking through sequential object IDs, a service account calling an endpoint it has never used, or a token used from two distant networks within minutes. Rate limits per credential bound the damage while someone investigates.

Adopt it incrementally

Few teams can rebuild their access control in one step, and they do not need to. A workable order is:

  1. List the services, the data each one holds and who calls it. The services holding the most sensitive data come first.
  2. Put token validation in every service, including internal ones, instead of only at the gateway.
  3. Add object-level authorization to every endpoint that takes an identifier, and write tests that request another tenant's object and expect a refusal.
  4. Turn on mutual TLS between services, starting in a permissive mode that logs unauthenticated calls before enforcing.
  5. Shorten credential lifetimes and narrow scopes once logging shows what each caller actually uses.

Each step is useful on its own and can be verified before the next one starts.

Summary

  • Zero trust means no request is trusted for its network location; internal services authenticate and authorize their callers too.
  • User authentication, including multi-factor, belongs to the identity provider. The API's job is to validate the token fully: signature, algorithm, issuer, audience and expiry.
  • Authorize per request against the specific resource, deny by default and fail closed. Missing object-level checks are the most common serious API flaw.
  • Encrypt internal traffic with TLS 1.2 or later, prefer mutual TLS between services, and treat certificate pinning as a deliberate choice with a rotation plan.
  • Log every access decision with the caller's identity and alert on changes in behaviour per credential.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading