javamicroservicesspring-cloudnetflix-eurekaapi-gateway

Dynamic Routing in API Gateway with Tenant-Based Service Resolution Using Spring Cloud and Eureka


I'm developing an application using the microservices architecture with Spring Boot and Spring Cloud. In this application, I want to use API Gateway and Eureka to enable dynamic routing. My main requirements are as follows:

Dynamic routing in API Gateway: The API Gateway should route incoming requests to services registered in Eureka dynamically. I do not want to define service names or addresses statically; the routing should be dynamic.

JWT authentication with tenant information: Users will log in using a JWT token, which contains tenant information. I want to update the target service of the request based on this tenant information.

I register my services in Eureka with the format "test-tenantId" and want the routing to align with this format. In the future, there may be multiple services with names like test-tenant1, test-tenant2, ..., test-tenantN. Therefore, I plan to apply the update only to requests that begin with /test, while other requests should be routed as-is based on Eureka's default routing.

I have two specific routing scenarios:

Scenario 1: When a request like /user/{id} is received, it should directly route to the service registered in Eureka with the name user. Scenario 2: When a request like /test/{page} is received, I want to modify this request to /test-{tenantId}/{page} based on the tenant information provided in the JWT token. For example, if the tenant in the token is tenant1, the request should be routed to /test-tenant1/{page}. How can I implement this dynamic routing and URL modification with API Gateway and Eureka? Could you provide an example structure or code?


Solution

  • I found it

    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_PREDICATE_MATCHED_PATH_ATTR, newServiceName);
        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_PREDICATE_PATH_CONTAINER_ATTR, newServicePath);
        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newUri);