NetflixOSS Zuul Filter for rejecting requests

Thomas Jäckle picture Thomas Jäckle · Jun 28, 2015 · Viewed 11.8k times · Source

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?

Answer

abeauchamp picture abeauchamp · Sep 9, 2015

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