Search code examples
springoauth-2.0microservicesspring-cloudspring-cloud-gateway

Adding client secret and client id to request in API Gateway


I have an Auth server sitting behind my Spring Cloud Gateway. I want to perform JWT auth through the Gateway. When I call the respective API Endpoint, I'm having to pass my username, password, client-id and client-secret to generate a JWT token.

User simply calls the endpoint with username and password, and the API gateway forwards the request to the Auth server after attaching client-id and client-secret. This is my whole plan.

My question is, how can I attach client id and client secret to my request, using Spring Cloud Gateway?

Thanks in advance!


Solution

  • You can create a java configuration as shown below:

    @Configuration
    public class SpringCloudConfig {
    
        @Bean
        public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
            return builder.routes()
                    .route(r -> r.path("/oauth/token")
                            .uri("http://localhost:8081/oauth/token")
                            .id("auth"))
                    .build();
        }
    }
    

    In this case, the original request and response will simply be proxied through the spring cloud gateway.

    For example, if spring cloud gateway is running on port 8080, the request will be (the authorization server is running on port 8081):

    curl --location --request POST 'http://localhost:8080/oauth/token' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --header 'Authorization: Basic c2VydmVyX2FwcDpzZWNyZXQ=' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'grant_type=client_credentials' \
    --data-urlencode 'client_id=server_app'
    

    You can add client-id, client-secret, or other data on the client.

    If you need to modify the request body you can add a filter:

    @Configuration
    public class SpringCloudConfig {
    
        @Bean
        public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
            return builder.routes()
                    .route(r -> r.path("/oauth/token")
                            .filters(f -> f.modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE,
                                    (exchange, body) -> {
                                        String modifiedBody = someService.modify(body);
                                        return Mono.just(modifiedBody);
                                    })
                            )
                            .uri("http://localhost:8081/oauth/token")
                            .id("auth"))
                    .build();
        }
    }