【问题标题】:Spring WebFlux add WebFIlter to match specific pathsSpring WebFlux 添加 WebFIlter 以匹配特定路径
【发布时间】:2019-04-04 10:29:09
【问题描述】:

在 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

非常感谢!

【问题讨论】:

  • 我真的很想用一种更简洁的方式来处理 webfilter 中的路径。

标签: java spring-security spring-webflux


【解决方案1】:

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

【讨论】:

  • 如何添加多条路径?
  • @Ilya Y 您可以定义一个 PathPattern 列表,其中包含所有路径的定义。
猜你喜欢
  • 2022-01-11
  • 2019-03-11
  • 2019-09-23
  • 1970-01-01
  • 2021-07-27
  • 2021-10-26
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
相关资源
最近更新 更多