'Spring WebFlux add WebFIlter to match specific paths
In the context of a spring boot application, I am trying to add a WebFilter to filter only requests that match a certain path.
So far, I have a filter:
@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
}
}
}
What I am trying to achieve is to remove the path matching from the filter and add it somewhere else more suitable, such as, from what I've read so far, a SecurityWebFilterChain.
Many thanks!
Solution 1:[1]
I've, maybe, a cleaner way to address your problem. It's based on code found in UrlBasedCorsConfigurationSource. It uses PathPattern that suits your needs.
@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
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael COLL |
