Search code examples
spring-bootspring-webfluxspring-cloud-gateway

How to pass data from GlobalFilter to controller


I have a GlobalFilter where I am creating one object and adding the same in attributes. When I try to get the same in my controller, I don't get it. How can I pass my custom object from filter to controller?

My filter:

public Mono<void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
   MyCustomObject obj = new MyCustomObject();
   exchange.getAttributes().put("MyObject", obj);
   return chain.filter(exchange);
}

My controller:

public ResponseEntity<String> getSomething(ServerWebExchange exchange) {
   MyCustomObject obj1 = exchange.getAttribute("MyObject"); // returns null
   MyCustomObject obj2 = exchange.getAttributes().get("MyObject"); // returns null
   .
   .
   .
}

What can be done to get this object which was created in filter in controller?

I tried ThreadLocal, but it did not work as SCG uses Spring WebFlux. Please share code as I'm new to Spring WebFlux.


Solution

  • GlobalFilter is a gateway filter, but you are using a controller instead of a route, so GlobalFilter cannot be executed. You can implement WebFilter:

    public class MyWebFilter implements WebFilter {
    
         @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            MyCustomObject obj = new MyCustomObject();
            exchange.getAttributes().put("MyObject", obj);
            return chain.filter(exchange);
        }
    
       
    }