问题
I am new to Spring Webflux. I want to use WebFilter to do authentication checking. So, the idea is intercepting the request, checking the Authorization header, and propagate the request
Here is what I have tried to do. I have successfully intercept the request and check whether the header is correct or not.
public class AuthWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
log.info("Request {} called", exchange.getRequest().getPath().value());
System.out.println("Tokent authenitcation..");
ServerHttpResponse response = exchange.getResponse();
getAuthorization(exchange.getRequest())
.doOnError(error -> exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED)))
.subscribe(authorization -> System.out.println(authorization));
return chain.filter(exchange);
}
private Mono<String> getAuthorization(ServerHttpRequest request) {
String authorization = request.getHeaders().getFirst(Authorization);
if (StringUtils.isBlank(authorization)) {
return Mono.error(
new UnauthorizedException(
Status.Unauthorized, "The request must provide authorization.", null));
}
return Mono.just(authorization);
}
}
The problem is I do not know how to break the flow if error happen. Although the status code is changed to 401, the response body still contain the requested data. In other words, it is count as a successful request, but only the status code is changed
Does anyone know what step do I miss here?
回答1:
Combine your code to a one chain like that:
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
log.info("Request {} called", exchange.getRequest().getPath().value());
System.out.println("Tokent authenitcation..");
ServerHttpResponse response = exchange.getResponse();
return getAuthorization(exchange.getRequest())
.doOnError(error -> exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED)))
.then(chain.filter(exchange));
}
If your authorization method emits error, chain of filter will not bean called.
来源:https://stackoverflow.com/questions/55467152/how-to-implement-authorization-header-checking-using-webfilter