如何在Zuul PRE_TYPE过滤器中发送HTTP响应

时间:2019-03-12 09:33:40

标签: spring-boot netflix-zuul

我想防止未登录的用户表单访问代理。我可以抛出异常,但是响应为404而不是`401或'403'。有可能吗?

过滤器代码:

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

}

1 个答案:

答案 0 :(得分:1)

可能有点晚了,但是我认为您可以删除ctx.sendZuulResponse(); 并添加ctx.setSendZuulResponse(false);