This service acts as the API Gateway and sole entry point in a microservice ecosystem. Built on the reactive Spring Cloud Gateway (WebFlux) framework, it provides high-throughput, non-blocking edge routing, load balancing, multi-tenant context enrichment, and frontline security enforcement.
173.5.52025.0.0Mavenspring-cloud-starter-gateway-server-webfluxspring-boot-starter-security, spring-boot-starter-oauth2-resource-servershared-serviceSpring Boot 3.5.x and Java 17+Security & Token Validation
As the edge proxy, this application is configured as an OAuth2 Resource Server validating stateless JSON Web Tokens (JWTs).
JWKS) endpoint.ReactiveJwtAuthenticationConverterAdapter to extract claims from the JWT payload and map them directly to standard Spring Security GrantedAuthority roles.JWT, failing CSRF verification, or violating CORS policies are blocked immediately at the edge. This protects downstream microservices from processing unauthorized or malicious traffic.Custom Gateway Filter Chain
Routing logic goes beyond basic path forwarding. Employed a custom MyGatewayFilter (implemented via GatewayFilter) applied explicitly inside a RouteLocator bean.
The gateway filter sequence enforces the following pipeline:
X-XSRF-TOKEN, tenant identifiers, or expected metadata). If any required header is missing, the request is immediately rejected with an appropriate HTTP error status (e.g., 400 Bad Request or 403 Forbidden) without forwarding.Identity Provider (IdP) Setup
Configure the application properties to locate the JWKS endpoint used to decode and verify signatures:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://auth-server.com/auth/.well-known/jwks.json
CORS & CSRF Mitigation
Because this is a web-facing boundary, strict cross-origin rules apply:
CorsWebFilter bean to manage cross-origin traffic explicitly.SPAs).Security Configuration
The gateway maintains a stateless SecurityWebFilterChain incorporating a global CorsWebFilter bean and cookie-backed CSRF mitigation optimized for Single Page Applications (SPAs).
Because standard Spring Security CSRF tokens are deferred (lazy) by default in reactive environments, a custom WebFilter is placed in the pipeline to explicitly subscribe to and flush the token cookie (CookieServerCsrfTokenRepository) on the client's initial metadata GET request.
// Conceptualized CSRF & Filter configuration within Configuration file
.csrf(csrf -> csrf
.csrfTokenRepository(cookieServerCsrfTokenRepository()) // Bean method name
.csrfTokenRequestHandler(new ServerCsrfTokenRequestAttributeHandler())
)
Filter Ordering: The custom CSRF activation filter is configured to execute immediately after SecurityWebFiltersOrder.CSRF to ensure it successfully forces token generation.
Dynamic Route Routing
Routes are explicitly managed as Java beans rather than raw configuration files to cleanly embed the custom filter logic.
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder, MyGatewayFilter gatewayFilter) {
return builder.routes()
.route("portfolio-service", r -> r.path("/portfolio/**")
.filters(f -> f.filter(gatewayFilter))
.uri("https://my-portfolio.com")
)
.build();
}
├───config/ #SecurityWebFilterChain, CorsWebFilter, CSRF and RouteLocator beans configured
├───filters/ #CSRF filter to trigger a token, Gatewat filter to validate authentication, authorization, tenant-info
└───properties/ #Java 17 configuration records
ADR 1: WebFlux over Spring MVC
spring-cloud-starter-gateway-server-webflux built on Netty.ThreadLocal cannot be used safely for multi-tenancy context propagation.ADR 2: Java Route Definitions over YAML
MyGatewayFilter).RouteLocator Java API.ADR 3: Edge-Enforced Multi-Tenancy Guardrails
HTTP 400 Bad Request or 403 Forbidden status. This completely shields downstream applications from un-scoped multi-tenant traffic and minimizes unnecessary computing overhead.Tracking Routing Decisions
If traffic is returning 404 Not Found or hitting the incorrect microservice, elevate the logging thresholds in local configuration profile to expose the gateway's internal evaluation pipeline:
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.security: DEBUG
Missing CSRF Cookie on Initial Load
If front-end applications fail because of a missing XSRF-TOKEN cookie, verify that the client application sends an initial metadata GET request. The custom CsrfFilter will not flush the cookie to the client until a subscription is explicitly triggered on that initial connection loop.
SecurityWebFilterChain, CorsWebFilter, and generalized security definitions out of this local project and directly into the internal shared library (shared-service). This will ensure that if additional gateway instances are spun up for other sub-domains, security protocols remain identical.