How to Specify custom filter in application.yml Spring Cloud Gateway

GOURAV MEHTA picture GOURAV MEHTA · Jan 12, 2018 · Viewed 9.6k times · Source

I have a custom gateway filter MYGatewayFilter.java file now i want to use this gateway filter with my route written in application.yml

 spring:
  cloud:
   gateway:
    routes:
      - id: login2_route
      uri: http://127.0.0.1:8083/login
      predicates:
       - Path: /login/
      filters:

How do i define filters for above route

Custom Filter MyGatewayFilter.java

public class MyGatewayFilter implements GatewayFilter {
    @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      ServerHttpRequest request;
      if(request.getHeaders().get("x-mydata")!=null){
         request= exchange.getRequest().mutate().header("my-new-header",request.getHeaders().get("x-mydata").get(0)).build();
      }

      return chain.filter(exchange.mutate().request(request).build());
  }
}       

Answer

devo picture devo · Jan 15, 2018

Instead of implementing GatewayFilter you should implement GatewayFilterFactory

and make it a Component:

@Component
public class MyGatewayFilter implements GatewayFilterFactory {

Then you can refer to it by the bean name in your route.

filters:
- MyGatewayFilter

The documentation on this isn't very good at the moment. I was only able to figure this out by looking at the source code for spring-cloud-gateway on github