Forbid Unauthenticated requests in Spring Cloud Gateway

三世轮回 提交于 2021-02-08 16:37:34

问题


I have implemented custom pre filter in spring cloud gateway which allows authenticated requests to go through the downstream process. What I want is if the request is unauthenticated then return with response of 401 UNAUTHORIZE status and stop the downstream processing. Can I achieve this spring cloud gateway.

Please help.

My filter code is below

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

and config is follows:

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

回答1:


See code in SetStatusGatewayFilterFactory

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


来源:https://stackoverflow.com/questions/53853345/forbid-unauthenticated-requests-in-spring-cloud-gateway

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