如何使用WebFilter实施授权标头检查

时间:2019-04-02 04:49:53

标签: java spring-boot spring-webflux

我是Spring Webflux的新手。我想使用WebFilter进行身份验证检查。因此,这个想法是拦截请求,检查Authorization标头并传播请求

这是我试图做的。我已经成功拦截了请求,并检查标题是否正确。

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);
  }
}

问题是如果发生错误,我不知道如何中断流程。尽管状态代码更改为401,但是响应主体仍包含请求的数据。换句话说,它被视为成功请求,但只有状态码被更改

有人知道我在这里错过哪一步吗?

1 个答案:

答案 0 :(得分:0)

将您的代码组合成这样的一个链:

@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));
}

如果您的授权方法发出错误,则不会调用bean的筛选器链。