如何使用WebFilter实现授权头检查

2022-04-06 00:00:00 java spring-boot spring-webflux

我是Spring Webflow的新手。我想使用WebFilter进行身份验证检查。因此,我们的想法是截取请求,检查授权标头,并传播请求

以下是我试图做的事情。我已成功拦截请求并检查头部是否正确。

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,但响应正文仍包含请求的数据。换句话说,它被视为成功请求,但只更改状态代码

有人知道我在这里错过了什么步骤吗?


解决方案

将您的代码组合为一个链,如下所示:

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

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

相关文章