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

Ale*_*tea 5 java spring-security spring-webflux

在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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想要达到的目的是从过滤器中删除匹配的路径,并将其添加到更合适的其他位置,例如,到目前为止,我已经阅读了SecurityWebFilterChain

非常感谢!

Mic*_*OLL 6

我可能有一种更简洁的方法来解决您的问题。它基于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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)