To write a Filtering Handler Function programmatically:
https://docs.spring.io/spring-framework/reference/web/webmvc-functional.html#webmvc-fn-handler-filter-function
https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/writing-custom-predicates-and-filters.html
In our application, we use a declarative approach, so here’s what I did:
Step 1: Create a custom ExceptionHandler:
public interface CustomGatewayFilterFunctions {
@Shortcut
static HandlerFilterFunction<ServerResponse, ServerResponse> handleAuthenticationException() {
return (request, next) -> {
// Your exception handler implementation
// example: if not ok then return return ServerResponse.status(UNAUTHORIZED).build();
return response;
};
}
class CustomGatewayFilter implements org.springframework.cloud.gateway.server.mvc.filter.FilterSupplier {
@Override
public Collection<Method> get() {
return Arrays.asList(CustomGatewayFilterFunctions.class.getMethods());
}
}
}
Step 2: In your resources/META-INF/spring.factories file, define your handler (create the file if it doesn't already exist).
# Override spring-cloud-gateway-server-mvc-4.1.0.jar!\META-INF\spring.factories
# to add Error Handler
org.springframework.cloud.gateway.server.mvc.filter.FilterSupplier=\
org.springframework.cloud.gateway.server.mvc.filter.Bucket4jFilterFunctions.FilterSupplier,\
org.springframework.cloud.gateway.server.mvc.filter.CircuitBreakerFilterFunctions.FilterSupplier,\
org.springframework.cloud.gateway.server.mvc.filter.FilterFunctions.FilterSupplier,\
your.path.to.CustomGatewayFilterFunctions.CustomGatewayFilter
Step 3: In your gateway declaration add you HandleAuthenticationException:
spring.cloud.gateway.mvc.routes[0].id=your_route
// Other declaration
spring.cloud.gateway.mvc.routes[0].filters[0]=HandleAuthenticationException
Then you should be able to debug your CustomGatewayFilterFunctions and add your desired behavior. If you want to know more, you can debug the method
GatewayMvcPropertiesBeanDefinitionRegistrar.getRouterFunction
-> Section // translate filters
Please note that I am using spring-cloud-gateway-server-mvc:4.1.0, so your implementation might differ slightly from this one, but the core concept remains the same.
For more detail, see Github ticket about @ControllerAdvice and @ExceptionHandler
https://github.com/spring-cloud/spring-cloud-gateway/issues/3335