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

时间:2018-10-31 09:34:26

标签: 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
            }
        }
    }

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

非常感谢!

1 个答案:

答案 0 :(得分:0)

也许,我可以采用一种更清洁的方式来解决您的问题。它基于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
        }
    }
}