10

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
JavaCodeNet
  • 1,115
  • 1
  • 15
  • 21

1 Answers1

24

See code in SetStatusGatewayFilterFactory

// set UNAUTHORIZED 401 response and stop the processing
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
Brian Rizo
  • 838
  • 9
  • 14
spencergibb
  • 24,471
  • 6
  • 69
  • 75
  • Now thats found here https://github.com/spring-cloud/spring-cloud-gateway/blob/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/SetStatusGatewayFilterFactory.java – Brian Rizo Dec 23 '21 at 20:31
  • if call `setComplete()` body response will be empty. please see https://github.com/spring-cloud/spring-cloud-gateway/issues/258 – someone Feb 10 '23 at 06:11