Security between services
Mid-level Frequently asked 5 min
On this page
The question
Which OAuth2 and OIDC flows matter in a microservices system, and when is each used?
30-second answer
OAuth2 issues access tokens; OIDC (OpenID Connect) adds an ID token that says who the user is. For a user in a browser or mobile app, use the authorization code flow with PKCE (Proof Key for Code Exchange): the user logs in at the authorization server, and the app trades a one-time code for tokens. For a service calling as itself, with no user, use client credentials. Implicit and password grants are deprecated.
Understand it
Log in once, relay the token downstream
Step by stepThe user opens the shop. The gateway, an OAuth2 client, redirects the browser to the authorization server with its client ID, the scopes it wants and a PKCE challenge.
View as text
The browser, the gateway and the authorization server along the top; Orders and Payments below. An arrow shows each message, solid for server-to-server calls and dashed for redirects through the browser, and a line says who holds the tokens.
The user opens the shop. The gateway, an OAuth2 client, redirects the browser to the authorization server with its client ID, the scopes it wants and a PKCE challenge.
The user logs in on the authorization server’s own page, with a password and perhaps a second factor. No service in the shop ever handles the password.
The authorization server redirects the browser back to the gateway with a short-lived, one-time authorization code. A code in a URL is useless on its own.
Server to server, the gateway trades the code, its secret and the PKCE verifier for access, refresh and OIDC ID tokens. The browser only gets a session cookie.
The browser calls /api/orders with its cookie. The gateway finds the session’s access token and relays it to Orders as an Authorization: Bearer header.
Orders validates the JWT itself, with the authorization server’s public keys, fetched once and cached: signature, issuer, audience and expiry. Then it checks the scope.
Orders calls Payments with the user’s token, or a narrower one from token exchange, over mutual TLS. Payments validates it too: being inside the network proves nothing.
The browser, the gateway and the authorization server along the top; Orders and Payments below. An arrow shows each message, solid for server-to-server calls and dashed for redirects through the browser, and a line says who holds the tokens.
The user opens the shop. The gateway, an OAuth2 client, redirects the browser to the authorization server with its client ID, the scopes it wants and a PKCE challenge.
The user logs in on the authorization server’s own page, with a password and perhaps a second factor. No service in the shop ever handles the password.
The authorization server redirects the browser back to the gateway with a short-lived, one-time authorization code. A code in a URL is useless on its own.
Server to server, the gateway trades the code, its secret and the PKCE verifier for access, refresh and OIDC ID tokens. The browser only gets a session cookie.
The browser calls /api/orders with its cookie. The gateway finds the session’s access token and relays it to Orders as an Authorization: Bearer header.
Orders validates the JWT itself, with the authorization server’s public keys, fetched once and cached: signature, issuer, audience and expiry. Then it checks the scope.
Orders calls Payments with the user’s token, or a narrower one from token exchange, over mutual TLS. Payments validates it too: being inside the network proves nothing.
Takeaway: With the authorization code flow, only the authorization server sees passwords and tokens never reach the browser. The gateway relays the access token, and each service validates it itself before trusting the caller.
In code
@Configuration
class SecurityConfig {
// spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.com/realms/shop
// spring.security.oauth2.resourceserver.jwt.audiences=orders
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/orders/**").hasAuthority("SCOPE_orders:read")
.requestMatchers(HttpMethod.POST, "/orders/**").hasAuthority("SCOPE_orders:write")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
}spring.security.oauth2.client.registration.shop.client-id=shop-gateway
spring.security.oauth2.client.registration.shop.client-secret=${GATEWAY_CLIENT_SECRET}
spring.security.oauth2.client.registration.shop.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.shop.scope=openid,orders:read,orders:write
spring.security.oauth2.client.provider.shop.issuer-uri=https://auth.example.com/realms/shop
spring.cloud.gateway.server.webflux.routes[0].id=orders
spring.cloud.gateway.server.webflux.routes[0].uri=lb://orders
spring.cloud.gateway.server.webflux.routes[0].predicates[0]=Path=/api/orders/**
# TokenRelay adds Authorization: Bearer with the logged-in user's access token
spring.cloud.gateway.server.webflux.routes[0].filters[0]=TokenRelay=@GetMapping("/orders/mine")
// Wrong: any caller on the network can send X-User-Id: someone-else
Wrong List<OrderView> mineWrong(@RequestHeader("X-User-Id") String userId) { return orders.byCustomer(userId); }
@GetMapping("/orders/mine")
// Right: the subject comes from a JWT whose signature, issuer and expiry were checked
Right List<OrderView> mine(@AuthenticationPrincipal Jwt jwt) { return orders.byCustomer(jwt.getSubject()); }Solve it
A nightly billing job must read every order, with no user logged in
The Billing service runs a job at 2 a.m. that reads the day’s orders from Orders to create invoices. Orders accepts
only valid JWTs with the scope orders:read. There is no user, so there is no user token to relay. The first draft
calls Orders with a shared admin password in a header. Design the job’s authentication.
- Name the caller. The job acts for itself, not for a user, so it needs its own identity: a confidential OAuth2 client registered for Billing.
- Pick the flow. The client credentials grant: Billing sends its client ID and secret, or a signed assertion, to the token endpoint and gets an access token for its own identity.
- Grant the least. Give the Billing client only
orders:read, with the Orders audience, so a leaked token cannot write orders or call other services. - Keep secrets out of code. Load the client secret from a secret store, rotate it, and let the library cache the token until it expires.
- Check. Call Orders with no token: 401. With Billing’s token: 200 on GET, 403 on POST.
// spring.security.oauth2.client.registration.billing-job.authorization-grant-type=client_credentials
// spring.security.oauth2.client.registration.billing-job.client-id=billing
// spring.security.oauth2.client.registration.billing-job.client-secret=${BILLING_CLIENT_SECRET}
// spring.security.oauth2.client.registration.billing-job.scope=orders:read
@Bean
RestClient orders(RestClient.Builder builder, OAuth2AuthorizedClientManager clients) {
var oauth = new OAuth2ClientHttpRequestInterceptor(clients);
oauth.setClientRegistrationIdResolver(request -> "billing-job"); // always the job's own identity
return builder.baseUrl("http://orders").requestInterceptor(oauth).build();
}
@Scheduled(cron = "0 0 2 * * *")
void invoiceYesterday() {
List<OrderView> day = orders.get().uri("/orders?date={d}", LocalDate.now().minusDays(1))
.retrieve().body(new ParameterizedTypeReference<>() {}); // Bearer token added for you
invoices.createFor(day);
}How to answer
- Services act as resource servers that validate tokens; the gateway or the app is the OAuth2 client.
- Access tokens are short-lived; refresh tokens get new ones without a new login.
- With a backend for frontend, tokens stay on the server and the browser holds a session cookie.
- Token exchange swaps a user's token for one meant for a specific downstream service.
Common mistakes
- Saying OAuth2 authenticates users. It authorizes access; OIDC is the identity layer on top.
- Storing access tokens in the browser's localStorage, where any injected script can read them.
Follow-up questions
How do you pass the user's identity from the gateway to services further down the call chain?
Pass the user's access token, a JWT (JSON Web Token), in the Authorization header on every hop, which Spring Cloud Gateway's TokenRelay filter does, and have every service validate it: signature with the issuer's public keys, issuer, audience, expiry, then scopes. For a tighter setup, exchange the token at each hop for one with a narrower audience and scope, so a leaked token works on fewer services.
- Never pass identity in a plain header such as X-User-Id; any caller can forge it.
- Validation is local and fast; keys are fetched once from the issuer and cached.
- Asynchronous messages carry the user ID as data, since tokens expire before old messages are read.
See it in the infographic: Log in once, relay the token downstream
Should authentication happen at the API gateway or in every service?
Both, with different jobs. The gateway handles the login flow and rejects requests without a valid token early, so bad traffic never reaches the services. Every service still validates the token and checks permissions for its own data, because the internal network is not a trust boundary: a compromised service or a misrouted request must not get in for free. This is the zero trust approach.
- The gateway knows coarse rules, such as a route needs a login; services know fine rules, such as whose order this is.
- Validating a JWT locally is cheap, so checking at every hop costs little.
- Object-level checks, such as order ownership, can only happen in the service that owns the data.
See it in the infographic: Log in once, relay the token downstream
What is mTLS, and why use it between services?
mTLS (mutual Transport Layer Security) is TLS where both sides present a certificate, so the client proves its identity to the server as well as the other way round. Between services it encrypts traffic and authenticates the calling service, not the user. A service mesh such as Istio or Linkerd issues, rotates and enforces the certificates in sidecars, so application code does not change.
- mTLS answers which service is calling; the JWT answers for which user and with which rights.
- Short-lived certificates, rotated automatically, limit the damage of a stolen key.
- Mesh policies can allow only Orders to call Payments, by service identity.
See it in the infographic: Log in once, relay the token downstream
What does PKCE protect against?
A stolen authorization code. The client makes a random verifier, sends its hash as the challenge in the redirect, and must present the verifier when it redeems the code. An attacker who intercepts the code, through a malicious app or a log, cannot redeem it without the verifier, which never left the client.
Check yourself
Show answers
- Client credentials: Correct. The job authenticates as itself and gets a token for its own identity.
- Authorization code with PKCE: Incorrect. That needs a user to log in through a browser.
- Resource owner password with an admin account: Incorrect. Deprecated, and it shares a person's password with a machine.
Show answers
- Yes, it checks the signature, audience and scopes itself: Correct. The inside of the network is not a trust boundary, and local validation is cheap.
- No, the gateway already checked it: Incorrect. Any compromised or misconfigured caller inside could then reach Orders freely.
- No, the gateway can pass the user ID in a header instead: Incorrect. A plain header can be forged by anyone who reaches Orders.