Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebFlux: How to abort request processing in WebFilter with provided response

I'd like to do something like below in my WebFilter to optionally bypass subsequent filters and RestControllers:

if(shouldRedirect(exchange)){
  //do redirect
}else if(!canAccess(exchange)){
  //return a 403 response
}else{
  chain.filter(exchange);
}

How am I supposed to do that?

Thanks

Leon

like image 831
anuni Avatar asked Jan 01 '23 20:01

anuni


1 Answers

Technically, the contract says that the filter has to return Mono<Void>, which completes when the exchange (request+response) has been processed.

The usual WebFilter does something on the request/response and then forwards the exchange to the next filter in the chain. But you can also unilaterally process the exchange and call it done.

In this sample, we're setting the status code and calling the response done.

class MyFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return response.setComplete();
    }

}
like image 58
Brian Clozel Avatar answered May 03 '23 15:05

Brian Clozel