Netflix Zuul-阻止请求路由 [英] Netflix Zuul - block request routing

查看:190
本文介绍了Netflix Zuul-阻止请求路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Zuul,我可以轻松定义自定义过滤器,这些请求在将请求转发到特定服务之前或之后被激活.

是否有办法阻止请求在预"过滤器级别转发,并立即将响应发送给客户端? 我知道可以使用静态"过滤器进行类似的操作,但是我需要根据每个请求来决定(基于请求本身中某些参数/标头的存在).

解决方案

以下是我如何使用zuul-filter检查授权的API密钥的示例.如果没有,我会向客户端发送401响应.

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

请注意,如果未授权客户端的API密钥,则所有其他筛选器仍将运行,但由于ctx.setSendZuulResponse(false),请求仍将失败. 响应失败时,默认情况下将为空-也就是说,没有诸如Content-Type之类的标头.最好自行设置它们,以便客户端的浏览器等知道如何解析响应正文. /p>

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).

解决方案

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.

这篇关于Netflix Zuul-阻止请求路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆