Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebFlux add WebFIlter to match specific paths

In the context of a spring boot application, I am trying to add a WebFilter to filter only requests that match a certain path.

So far, I have a filter:

    @Component
    public class AuthenticationFilter implements WebFilter {

        @Override
        public Mono<Void> filter(ServerWebExchange serverWebExchange,
                             WebFilterChain webFilterChain) {
        final ServerHttpRequest request = serverWebExchange.getRequest();

            if (request.getPath().pathWithinApplication().value().startsWith("/api/product")) {
               // logic to allow or reject the processing of the request
            }
        }
    }

What I am trying to achieve is to remove the path matching from the filter and add it somewhere else more suitable, such as, from what I've read so far, a SecurityWebFilterChain.

Many thanks!

like image 213
Alexandru Bottea Avatar asked Oct 31 '18 09:10

Alexandru Bottea


1 Answers

I've, maybe, a cleaner way to address your problem. It's based on code found in UrlBasedCorsConfigurationSource. It uses PathPattern that suits your needs.

@Component
public class AuthenticationFilter implements WebFilter {

    private final PathPattern pathPattern;

    public AuthenticationFilter() {
        pathPattern = new PathPatternParser().parse("/api/product");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange,
                         WebFilterChain webFilterChain) {
    final ServerHttpRequest request = serverWebExchange.getRequest();

        if (pathPattern.matches(request.getPath().pathWithinApplication())) {
           // logic to allow or reject the processing of the request
        }
    }
}
like image 63
Michael COLL Avatar answered Nov 02 '22 23:11

Michael COLL