Centralizing authentication and authorization at the API Gateway means validating tokens and enforcing access policy once, at the entry point, before requests ever reach downstream microservices.
Key Points: • The gateway validates the bearer token (JWT or via introspection against an OAuth2 server) on every inbound request. • Invalid, expired, or missing tokens are rejected at the edge, so unauthorized traffic never reaches internal services. • Coarse-grained authorization (e.g., role or scope checks) can happen at the gateway, while fine-grained business rules stay in each service. • Spring Cloud Gateway can integrate a GatewayFilter or Spring Security's resource-server support to enforce this centrally. • This reduces duplicated security logic across services and shrinks the internal attack surface, though services should still validate propagated identity for defense in depth.
Example: Spring Cloud Gateway is configured with a global filter that checks for a valid JWT on every route; requests without one are rejected with 401 before ever reaching the order-service or inventory-service behind it.
Code Example:
@Bean
public SecurityWebFilterChain gatewaySecurity(ServerHttpSecurity http) {
return http
.authorizeExchange(ex -> ex
.pathMatchers("/public/**").permitAll()
.anyExchange().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}Interview Tip: A concise interview answer is:
"I'd configure the gateway as an OAuth2 resource server that validates the JWT on every incoming request before routing to downstream services. That way authentication and coarse authorization happen once at the edge, so each microservice doesn't have to duplicate token validation logic, though services can still enforce their own fine-grained rules."