How to implement authorization header checking using WebFilter

浪尽此生 提交于 2020-12-15 19:08:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!