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.