Posted on

Writing custom gateway filter factories

How to create custom Spring Cloud Gateway filter – GatewayFilterFactory

In this tutorial, you’ll learn how to create a custom Spring Cloud Gateway filter class by extending GatewayFilterFactory. This specific example will show you how to deal with a situation where OAuth token is passed as a path variable where the request needs to be mutated to move this token to the Authorization header.

Not so long ago I had an uncommon request from my FE team and that is to somehow allow security OAuth token to be passed as path variable instead of through Authorization header. Why would someone need something like this, you could ask – they had an issue with some Angular text editor library where it would be very hard and time-consuming for them to fork it and add missing “add header” functionality. Since time was a critical factor, we decided to implement the custom filter on the Gateway service by implementing the GatewayFilterFactory interface.


Config class is used for storing configuration properties for my custom filter. I didn’t need anything like that, so I left it empty. Don’t forget to annotate this class with @Component.

So, what is exactly happening in the filter code?

First, we get URL String and split it by “/” to extract our token.

Since we had to base64 encode token before sending, we decode it to get a real token.

Then we put it in Authorization header and mutate our request that way. And that’s it, we have our token on the way in Authorization header instead of a path.

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

Why is this -1? I am trying to figure out the same thing, there is no documentation on how to add a custom filter to a route.

did you solve the problem, I am facing the same problem but I still did not success after tried the [email protected] MEHTA

3 Answers 3

Instead of implementing GatewayFilter you should implement GatewayFilterFactory

and make it a Component:

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

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

Pay attention that the PropertiesRouteDefinitionLocator removes the final part of the filter name if it is equal to RoutePredicateFactory or GatewayFilterFactory . See: PropertiesRouteDefinitionLocator , FilterDefinition , NameUtils . So if your filter is in class PrincipalNameGatewayFilterFactory you have to configure the route with filter name PrincipalName .