Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HTTP Error 401 Code & Skip Filter Chains

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:

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, I could do the following:

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

OR

(2) throw an exception that, eventually, results in Spring Security throwing a 401 error to the client.

If #1 is the better option, how can I skip the filter chain after calling setStatus(401) on the response?

Or, if #2 is the right way to go, which exception should I throw?

like image 200
Kevin Meredith Avatar asked May 13 '14 00:05

Kevin Meredith


People also ask

Why am I getting a 401 error?

The 401 Unauthorized error is an HTTP status code that means the page you were trying to access cannot be loaded until you first log in with a valid user ID and password. If you've just logged in and received the 401 Unauthorized error, it means that the credentials you entered were invalid for some reason.

How do I return a 401k in Java?

For error status codes like 401, use the more specific sendError(): httpResponse. sendError(HttpServletResponse. SC_UNAUTHORIZED, "your message goes here");


2 Answers

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);         }     } 
like image 76
Cyva Avatar answered Sep 21 '22 09:09

Cyva


From the API docs for the doFilter method, you can:

  • Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()),
  • or not pass on the request/response pair to the next entity in the filter chain to block the request processing

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

like image 37
Shaun the Sheep Avatar answered Sep 18 '22 09:09

Shaun the Sheep