禁止 Spring 云网关中未经身份验证的请求

Forbid Unauthenticated requests in Spring Cloud Gateway

我在 spring 云网关中实现了自定义预过滤器,它允许经过身份验证的请求通过下游过程。我想要的是,如果请求未经身份验证,则 return 响应 401 UNAUTHORIZE 状态并停止下游处理。我可以实现这个 spring 云网关吗?

请帮忙。

我的过滤代码如下

public class ValidUserFilter implements GatewayFilterFactory {

  @Override
  public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {
      ServerHttpRequest request = exchange.getRequest();

      if (isValidRequest(request)) {
        // Allow processing
      } else {
      // set UNAUTHORIZED 401 response and stop the processing
      }

      return chain.filter(exchange);
    };
  }
}

配置如下:

  - id: myroute
            uri: http://localhost:8080/bar
            predicates:
            - Path=/foo/**
            filters:
            - ValidUserFilter

SetStatusGatewayFilterFactory

中的代码
// set UNAUTHORIZED 401 response and stop the processing
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();