Netflix Zuul - block request routing

时光毁灭记忆、已成空白 提交于 2019-12-23 13:07:47

问题


With Zuul I can easily define custom filters that are activated before or after the request is forwarded to the specific service.

Is there a way to block requests from being forwarded at a "pre" filter level, and send immediately the response to the client? I know something similar is doable with "static" filters, but I need to decide per request (based on the presence of certain parameters/headers in the request itself).


回答1:


Here is an example of how I use zuul-filter to check for an API-key being authorized. If not, I send a 401 response to the client.

 @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String apiKey = request.getHeader("X-API-KEY");
        if (!isAuthorized(apiKey)){
            // blocks the request
            ctx.setSendZuulResponse(false);

            // response to client
            ctx.setResponseBody("API key not authorized");
            ctx.getResponse().setHeader("Content-Type", "text/plain;charset=UTF-8");
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        return null;
    }

Note that if the client's API key is not authorized, all other filters will still be run, but the request will still fail due to ctx.setSendZuulResponse(false). When failing a response, it will by default be empty - that is, there is no headers such as Content-Type etc. It is a good idea to set them yourself so a client's browser etc. knows how to parse the response body.




回答2:


I use a pre filter to check the authentication of the request, and if the request dose not authorized, then I return 401 and do not call the back end service any more. I do it in run() function like this:

    RequestContext ctx = getCurrentContext();
    // do something to check the authentication
    if(auth failed){
      ctx.unset();
      ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    }

ctx.unset() tell the context to stop this request, and ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); set the http code to 401




回答3:


I found the solution, just needed to add context.setSendZuulResponse(false); in the run() method of my "pre" custom filter.

Other filters will still be called, but request won't be routed to destination.



来源:https://stackoverflow.com/questions/37243381/netflix-zuul-block-request-routing

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