Search code examples
spring-bootnetflix-zuul

How to send a HTTP response in Zuul PRE_TYPE Filter


I want to prevent not logged user form accessing the proxy. I can throw an exception but the response is 404 instead of `401 or '403'. It it possible?

Filter code:

@Component
public class CustomZuulFilter extends ZuulFilter {


    //FIXME - if 401,403 get the new token??, fallbackMethod = "fall",
    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
            }
    )
    @Override
    public Object run() {
        logger.debug("Adding zulu header");
        String userName = getLoggedUser();
        RequestContext ctx = RequestContext.getCurrentContext();
        if (userName == null) {
           // throw new RuntimeException("User not authenticated");
            logger.info("User not authenticated");
            ctx.setResponseStatusCode(401);
            ctx.sendZuulResponse();
            return null;
        }

        return null;
    }


    private String getLoggedUser() {
       [...]
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1; 
    }

}

Solution

  • It might be a bit late, but i think you can remove ctx.sendZuulResponse(); and add ctx.setSendZuulResponse(false);