Spring WebFlux添加WebFIlter以匹配特定路径

2022-04-06 00:00:00 java spring-webflux spring-security

在Spring Boot应用程序的上下文中,我尝试添加一个WebFilter以仅筛选与特定路径匹配的请求。

到目前为止,我有一个过滤器:

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

我试图实现的是从筛选器中删除路径匹配,并将其添加到其他更合适的位置,例如,从我到目前为止读到的内容,SecurityWebFilterChain

非常感谢!


解决方案

我可能有一种更清晰的方法来解决您的问题。它基于UrlBasedCorsConfigurationSource中的代码。它使用PathPattern满足您的需求。

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

相关文章