Background
I want to implement the design presented in this article.
It can be summarised by the diagram below:
Add the following within your run method, it will solve this problem
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
I know I am very late to answer You can approach with prefilter of zuul. The steps you have to follow is given below.
//1. create filter with type pre
//2. Set the order of filter to greater than 5 because we need to run our filter after preDecoration filter of zuul.
@Component
public class CustomPreZuulFilter extends ZuulFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Object run() {
final RequestContext requestContext = RequestContext.getCurrentContext();
logger.info("in zuul filter " + requestContext.getRequest().getRequestURI());
byte[] encoded;
try {
encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8"));
requestContext.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
final HttpServletRequest req = requestContext.getRequest();
if (requestContext.getRequest().getHeader("Authorization") == null
&& !req.getContextPath().contains("login")) {
requestContext.unset();
requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
} else {
//next logic
}
}
} catch (final UnsupportedEncodingException e) {
logger.error("Error occured in pre filter", e);
}
return null;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public int filterOrder() {
return 6;
}
@Override
public String filterType() {
return "pre";
}
}
requestContext.unset() will Resets the RequestContext for the current threads active request. and you can provide a response status code.
You could try setting setSendZuulResponse(false)
in the current context. This should not route the request. You could also call removeRouteHost()
from the context, which would achieve the same. You could usesetResponseStatusCode
to set the 401 status code.