Alexandru Bottea
Alexandru Bottea

Reputation: 91

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!

Upvotes: 9

Views: 7437

Answers (1)

Micha&#235;l COLL
Micha&#235;l COLL

Reputation: 1297

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
        }
    }
}

Upvotes: 9

Related Questions