NetflixOSS Zuul Filter for rejecting requests

南笙酒味 提交于 2019-12-04 16:16:43

问题


I am trying to use a ZuulFilter in a simple spring-cloud-Netflix Api gateway (reverse proxy) in order to authenticate requests against a custom authentication provider (via Rest call).

The Filter should reject unauthorized requests with a 401 and don't pass those requests further down to the proxied services.

Is that even possible for a ZuulFilter? I did not find documentation, example or something in Zuuls api.

Any suggestions?


回答1:


I got this to work, took some digging. Make sure your request isn't cached already. Just call this method from your run() method inside your ZuulFilter.

/**
 * Reports an error message given a response body and code.
 * 
 * @param body
 * @param code
 */
private void setFailedRequest(String body, int code) {
    log.debug("Reporting error ({}): {}", code, body);
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(code);
    if (ctx.getResponseBody() == null) {
        ctx.setResponseBody(body);
        ctx.setSendZuulResponse(false);
    }
}



回答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

also see Netflix Zuul - block request routing




回答3:


If you want to use authentication with the Spring Cloud then try the Spring Security Cloud project.



来源:https://stackoverflow.com/questions/31099368/netflixoss-zuul-filter-for-rejecting-requests

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