Using a custom Spring Security filter, I\'d like to return an HTTP 401 error code if the HTTP Header doesn\'t contain a particular key-value pair.
Example:
Just do as they say in the upper answer. "so setting the response status code and returning immediately" This is just type:
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
From the API docs for the doFilter method, you can:
so setting the response status code and returning immediately without invoking chain.doFilter
is the best option for what you want to achieve here.
I suggest this solution below.
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
final String val = request.getHeader(FOO_TOKEN)
if (val == null || !val.equals("FOO")) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is not valid.");
} else {
chain.doFilter(req, res);
}
}
So you can use something like this.
@Override
public void doFilter() {
if (whiteListOrigins.contains(incomeOrigin)) {
httpResponse.setHeader("Access-Control-Allow-Origin", incomeOrigin);
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "Not Allowed to Access. Please try with valid Origin.");
}
}