在Spring Cloud Gateway中禁止未经身份验证的请求

时间:2018-12-19 14:30:52

标签: spring spring-boot spring-cloud spring-cloud-gateway

我已经在Spring Cloud Gateway中实现了自定义的预过滤器,该过滤器允许经过身份验证的请求通过下游流程。我想要的是如果请求未经身份验证,然后返回401 UNAUTHORIZE状态的响应并停止下游处理。我可以实现这个春季云网关吗?

请帮助。

我的过滤器代码在下面

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

1 个答案:

答案 0 :(得分:1)

查看SetStatusGatewayFilterFactory中的代码

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