URL Pattern filtering in Spring Webflux WebFilterChain

Viewed 2206

I am trying to write a filter in Spring Webflux, but am unable to find an option to apply the filter only to certain URL patterns. In the Spring MVC world, this can be achieved using

FilterRegistrationBean.addUrlPatterns("/protected/*");

But I am unable to find an equivalent for it in the webflux world.

As a workaround, I am using the following, but it obviously is not the right way to do it

String path = serverWebExchange.getRequest().getURI().getPath();
if(path.contains("/protected/"))
<do-something>

Is there any Spring Webflux native URL pattern matching method in WebFilterChain that I can use to apply the filter to only a specific set of URLs ? Thanks !

1 Answers

Webflux and Spring MVC are not the same so you can't expect there to be the same functionailty in both libraries.

If you look into the CorsWebFilter class in webflux you will see they have implemented the path registering themselves.

They set a path in a UrlBasedCorsConfigurationSource and then in this they use a PathPatternParser to register configurations to each path.

/**
 * Register a {@link CorsConfiguration} for the specified path pattern.
 */
public void registerCorsConfiguration(String path, CorsConfiguration config) {
    this.corsConfigurations.put(this.patternParser.parse(path), config);
}

Registering a cors filter:

@Bean
public CorsWebFilter corsWebFilter() {
    final CorsConfiguration config = new CorsConfiguration();

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}

so what you are looking for doesn't exist specifically but looking into the Spring code you can see what they are doing and build something similar that fits your need.

Another option is to register the filter only to the endpoints you want it to be active on using the Routerfunction::filter and implementing a HandlerFilterFunction

Related