Error HTTP Error 401.

Using a special Spring Security filter, I would like to return an HTTP 401 error code if the HTTP header does not contain a specific key-value pair.

Example:

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")) { // token is not valid, return an HTTP 401 error code ... } else { // token is good, let it proceed chain.doFilter(req, res); } 

As I understand it, I could do the following:

(1) ((HttpServletResponse) res).setStatus(401) and skip the rest of the filter chain

OR

(2) throws an exception that ultimately leads to Spring security throwing a 401 error to the client.

If # 1 is the best option, how can I skip the filter chain after calling setStatus(401) in the answer?

Or, if # 2 is the right way, what exception should I throw?

+7
spring security
source share
2 answers

In the API documents for the doFilter method, you can:

  • Or call the next object in the chain using the FilterChain object (chain.doFilter ()),
  • or do not pass a request / response pair to the next object in the filter chain to block request processing

so setting a response status code and returning immediately without calling chain.doFilter is the best option for what you want to achieve here.

+11
source

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); } } 
+2
source

All Articles