Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Security

Authentication and Authorization Between Services

Secure calls between microservices: JWT validation at the gateway, service-to-service tokens, mTLS, zero trust and scopes, with signed-token code you can run.

In a monolith, security is mostly at the front door: once a request is inside, every function trusts every other. In microservices, "inside" is a network full of independent services, and any of them could be compromised, misconfigured or simply called by the wrong caller. Two questions must be answered on every call, and they are different questions.

Authentication asks who are you? Authorization asks what are you allowed to do? In microservices there are two kinds of "you": the end user on whose behalf the request is made, and the calling service itself. This lesson shows how to handle both, with tokens, certificates and scopes.

Two questions, two callers

Authentication Prove who you are.
Authorization Decide what you may do.
The user Who started the request.
The service Who is making this call.
1 / 2

Don't trust the network

An old model said: build a strong wall (a firewall) around the data center, and treat everything inside as friendly. That fails for microservices. One vulnerable service gives an attacker a foothold inside the wall, and from there every unauthenticated internal API is open. Cloud networks, containers and VPNs blur the "inside" anyway.

Zero trust is the opposite stance: never trust, always verify. Every call is authenticated and authorized, whether it comes from the internet or from the service next door, and traffic is encrypted everywhere. You still keep network controls (they reduce exposure), but they are a layer, not the whole defense.

Tokens and JWTs

Re-sending a password with every request is a bad idea, so after login the user receives a token: a short-lived proof of identity that services can check. The most common format is the JSON Web Token (JWT), three base64url parts joined by dots:

TEXT
<header>.<payload>.<signature>
  • The header names the signing algorithm.
  • The payload holds claims: sub (the subject, such as a user id), iss (issuer), aud (the audience: which service the token is for), exp (expiry time), iat (issued at) and custom ones like scope.
  • The signature covers header and payload. Anyone can read a JWT, because it is only encoded, not encrypted; but nobody can change it without invalidating the signature.

So never put secrets in a JWT. Verification means recomputing the signature and checking the claims. The stand-in below does this with node:crypto. It uses a shared secret (HS256) to keep the code short, and it demonstrates the checks every verifier must make, including the classic attacks: tampered payload, expired token, wrong audience, wrong secret, and the alg: none trick, where an attacker claims "no signature needed". A verifier must decide which algorithm it accepts, never take it from the token.

Node.js Issuing and verifying a signed token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the untouched, unexpired token meant for orders passes. The tampered token tried to upgrade its scope to admin but kept the old signature, so the signature check fails. Two details worth copying: the comparison uses timingSafeEqual, which takes the same time whatever the mismatch, so an attacker cannot learn the signature byte by byte from response times; and the clock is passed in, which makes the code easy to test. Production code should use a vetted library, not hand-rolled verification: this lesson shows what the library does.

JWT at the gateway

Where should user tokens be checked? A common design is to validate at the gateway (API Gateway and Backend for Frontend). The gateway receives the user's token, verifies signature, expiry and audience, and rejects bad requests before they cost the backend anything. That centralizes login logic and keeps internal services simpler.

But "validated once at the edge, trusted everywhere" is exactly the soft-center that zero trust avoids. Better practice is:

  • The gateway validates the user token and forwards the identity, either by passing the token or by minting a short-lived internal token for the request.
  • Each service still verifies the token itself (cheap with signatures) or accepts identity only from a channel it can authenticate, such as mTLS from the gateway.
  • Each service makes its own authorization decisions, because only it knows what orders:write means for its data.

Tokens should be short-lived (minutes), because a JWT cannot easily be revoked before it expires. Long sessions use a refresh token, kept server-side or in a protected store, that can be revoked.

Asymmetric signing

With a shared secret (HS256), every service that can verify a token can also forge one. That is risky across many teams. Production systems usually use asymmetric signatures (RS256, ES256 or EdDSA): the authorization server signs with a private key, and services verify with the matching public key, which is not secret. Public keys are published at a JWKS endpoint, and services cache them and pick the right one by the key id (kid) in the header, which also makes key rotation possible (Securing the Edge, Data and Secrets).

Service-to-service identity

When orders calls payments, two identities matter: the user who started the checkout, and the orders service itself. There are two common patterns.

  1. Propagate the user's token. orders passes the token on. payments sees the user, but any service holding the token can now do anything the user could, including things unrelated to the original request (the "confused deputy" problem). Use this only with a narrow audience and scope.
  2. Exchange it for a service token. orders asks the authorization server for a new, narrow, short-lived token for payments, with aud: payments, a minimal scope, and a claim naming the acting service. (OAuth 2.0 has a standard, Token Exchange, for this; the claim here is simplified.) For background jobs with no user, services use the client credentials flow, where the service authenticates with its own credentials and receives a token for itself.

Scopes and authorization

A scope names a permission: orders:read, orders:write, payments:charge. The token lists the scopes granted, and each service checks that the one required for this endpoint is present. Scopes are coarse; finer decisions (this user may only see their own orders) belong in service code, using claims like sub. Keep the rule least privilege: a token gets only the scopes and audience it needs, for as short a time as possible.

The second stand-in has three services trusting one issuer. This time it uses real asymmetric signing (Ed25519, via node:crypto): only the auth server holds the private key, and services verify with the public key. It shows a user calling orders, a token meant for the wrong service, a service-to-service token that records the acting service, a missing scope, an attacker who signs with their own key, and an expired token.

Node.js Scopes, audiences and service-to-service tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each rejection has the right status code. 401 means "I cannot establish who you are" (bad signature, expired); 403 means "I know who you are, and you may not do this" (wrong audience, missing scope). The token meant for orders is useless at payments, which limits the damage if one service leaks the tokens it receives. The attacker used a key pair with the same issuer name, but the verifier only trusts the real public key, so the signature fails: trust comes from keys, never from names in claims.

mTLS: identity for the connection

Tokens identify a request. Mutual TLS (mTLS) identifies the connection. In ordinary TLS (the padlock in your browser), only the server shows a certificate. In mTLS, both sides present certificates signed by a certificate authority both trust, so each knows exactly which service is on the other end, and the traffic is encrypted.

Managing certificates by hand for hundreds of services is painful, so teams use a service mesh (Istio, Linkerd and others) or a platform that issues short-lived certificates to each workload automatically and enforces mTLS in a sidecar or node proxy, without application changes. A mesh policy that requires mTLS looks like this (real configuration, read-only; the API version depends on your Istio release):

YAML
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT

mTLS proves which service is calling; tokens prove which user and which permissions. They complement each other: mTLS between services for transport identity, tokens for user identity and scopes.

A checklist

  • Authenticate and authorize every call, including internal ones (zero trust).
  • Short-lived, signed tokens; verify signature, expiry, issuer and audience; accept only the algorithms you expect.
  • Prefer asymmetric signing and key rotation via published public keys.
  • Narrow tokens per call (audience and least-privilege scopes); use client credentials for service-only work.
  • Make authorization decisions inside each service, not only at the gateway.
  • Use mTLS (usually through a mesh) for service identity and encryption in transit.
  • Never log tokens or put secrets in them.

What is real and what is the stand-in

JWT structure, claims, signature checks, scopes, 401 versus 403, client credentials and mTLS are the real mechanisms. The TryIts use real node:crypto signatures, but everything runs in one process with a fixed clock: there is no authorization server, no key distribution and no network. The simplified act claim differs from the object form used by the OAuth token exchange standard. The Istio snippet is real but read-only.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between 401 and 403?

    Authentication failures return 401; authorization failures (wrong audience, missing scope) return 403.
  2. 2. Why is a JWT payload not a place for secrets?

    The signature prevents changes, but the payload is readable. Never place passwords or private data in it.
  3. 3. Why does a verifier choose the accepted algorithm itself instead of trusting the token header?

    If the token chooses its own verification rules, an attacker can ask for none. The verifier must enforce what it accepts.
  4. 4. What is the benefit of asymmetric signing (public/private keys) for tokens?

    Only the issuer holds the private key. Verifiers use the public key, so a compromised service cannot mint tokens.
  5. 5. What does mTLS add compared with ordinary TLS?

    In mutual TLS the calling service also proves its identity with a certificate, besides encrypting traffic.

Summary

  • Authentication asks who you are; authorization asks what you may do. Microservices must answer for both the user and the calling service.
  • Zero trust means verifying every call, even inside the cluster.
  • JWTs are signed, readable claims: verify signature, expiry, issuer and audience, and choose the algorithm yourself. Keep them short-lived.
  • Validate at the gateway for efficiency, but let each service verify tokens and decide its own authorization with scopes and least privilege.
  • Use narrow, exchanged tokens for service-to-service calls, and mTLS (often through a mesh) for service identity and encryption.

Next: Securing the Edge, Data and Secrets.