Indraneel Bende
Indraneel Bende

Reputation: 3486

How to add a custom filter specific to a route in Spring Cloud Gateway

So I am new to spring cloud gateway and have just started playing around with it . I was going through the documentation and stumbled upon how to create a custom filter.

https://cloud.spring.io/spring-cloud-gateway/reference/html/#developer-guide

So this is my code for creating a custom filter -

       @Component
      public class CustomPreFilterFactory extends AbstractGatewayFilterFactory<CustomPreFilterFactory.Config> {


      public static class Config {
        //Put the configuration properties for your filter here
      }

     @Override
     public GatewayFilter apply(Config config) {

       return (exchange,chain) ->{
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
        System.out.println("Request came in custom pre filter");
        return chain.filter(exchange.mutate().request(builder.build()).build());
      };
    }
  }

Now , I am using java route api provided by gateway for configuring my routes , so this is my route code -

        @Bean
      public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder) 
{
      return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").uri("http://localhost:8081"))
        .build();
}

Now , I want to know how to add the custom filter factory which i just created to the route defined above programmatically .

I have looked at the following examples where they register a custom filter factory -

  1. https://www.javainuse.com/spring/cloud-filter
  2. https://medium.com/@niral22/spring-cloud-gateway-tutorial-5311ddd59816

Both of them create routes using properties rather than using the route api .

Any help is much appreciated.

Upvotes: 4

Views: 9508

Answers (3)

Shivam Bhavsar
Shivam Bhavsar

Reputation: 11

This solution worked for me, I created an OrderedGatewayFilter with the injected CustomGatewayFilterFactory like this and added that filter to routes:

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder, CustomGatewayFilterFactory customGatewayFilterFactory) 
{
    OrderedGatewayFilter orderedGatewayFilter =
      new OrderedGatewayFilter(customGatewayFilterFactory.apply(config), 45);
    return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").uri("http://localhost:8081").filter(orderedGatewayFilter))
        .build();
}

Upvotes: 1

rakesh mehra
rakesh mehra

Reputation: 642

You need to inject your custom Filter and include it in the route. Something like this..

        @Bean
      public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder, CustomPreFilterFactory cpf) 
{
      return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").filters(f -> f.filter(myCustomFilter.apply(new Config()))).uri("http://localhost:8081"))
        .build();
}

Upvotes: 0

Vijay
Vijay

Reputation: 663

Below is an example of a route that has a predicate defined to match all the request URL with /api/v1/first/** and apply a pre-filter to rewrite the path. There is another filter applied to modify the request header and then route the request to load balanced FIRST-SERVICE.

builder.routes()
            .route(r -> r.path("/api/v1/first/**")
                    .filters(f -> f.rewritePath("/api/v1/first/(?.*)", "/${remains}")
                                    .addRequestHeader("X-first-Header", "first-service-header")
                    )
                    .uri("lb://FIRST-SERVICE/") //downstream endpoint  lb - load balanced
                    .id("queue-service"))

            .build();

Below is the equivalent .yaml configuration.

spring:
  cloud:
    gateway:
      routes:
      - id: first-service
        uri: lb://FIRST-SERVICE
        predicates:
        - Path=/api/v1/first/**
        filters:
        - RewritePath=/api/v1/first/(?.*), /$\{remains}
        - AddRequestHeader=X-first-Header, first-service-header

You can find more such filters in this link.

Hope this is what you are looking for.

Upvotes: 0

Related Questions