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());
}
}
Implementing Spring Cloud Gateway Filters using Java Configuration. In the FirstController we extract the request header we have added in the pre filter and print it. In the SecondController we extract the request header we have added in the pre filter and print it. Run the application.
Spring Cloud Gateway Architecture Using this functionality we can match HTTP request, such as headers , url, cookies or parameters. Filter: These are instances of Spring Framework GatewayFilter. Using this we can modify the request or response as per the requirement.
A gateway filter is a spam filter that mailbox providers and corporate domains use on the inbound mail transfer agent (MTA), also referred to as the gateway, before they accept mail into their network for further filtering and processing.
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
You need to implement GatewayFilterFactory
@Component
public class DemoGatewayFilter implements GatewayFilterFactory<DemoGatewayFilter.Config> {
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
System.out.println("gateway filter name "+config.getName());
return chain.filter(exchange);
};
}
@Override
public Config newConfig() {
return new Config("DemoGatewayFilter");
}
public static class Config {
public Config(String name){
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
and in application.yml file
spring:
application:
cloud:
gateway:
routes:
- id: MayApplication
uri: http://myapplication:8080
predicates:
- Path=/apipath/to/filter/**
filters:
- DemoGatewayFilter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With