在 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
}
}
}
关于java - Spring WebFlux添加WebFIlter匹配特定路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53080263/