Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Request header values in Spring Cloud Gateway

I am implementing API routing using spring cloud gateway, in one of the use cases I need to get the header value from incoming request and use it for some processing, further add this processed value to outgoing (routed) API call as header. How to get the header value from an incoming API call in routeBuilder?

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder) {
    return routeBuilder.routes()
        .route(r -> r.path("/api/v1/**")
        .setRequestHeader("testKey", "testValue")
        .uri("URL"))
        .build();
}
like image 633
TechSeeker Avatar asked Oct 26 '25 09:10

TechSeeker


1 Answers

You Can write a custom filter for the same. Its just a way around, not sure what is the best way for doing this:

public class SomeFilterFactory
        extends AbstractGatewayFilterFactory<SomeFilterFactory.SomeConfig> {



    public SomeFilterFactory() {
        super(SomeFilterFactory.SomeConfig.class);
    }

    @Override
    public GatewayFilter apply(SomeFilterFactory.SomeConfig config) {

        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String someHeader = request.getHeaders().getFirst("someHeader");
            // do your things here
            return chain.filter(exchange);
        };
    }

    public static class SomeConfig {
        // your config if required
        // or use name value config

    }

}
like image 105
Arpan Das Avatar answered Oct 28 '25 02:10

Arpan Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!