0

I'm using a filter in order to check if an authorization bearer token is valid. Nevertheless, I'm strugling with the fact that user-agent(firefox, chrome...) is trying to request a CORS OPTIONS request before making the "real" request.

So, my filter intercepts this OPTIONS request, and it has no any authorization bearer token, so it responds with an 4xx http code.

Should I avoid OPTIONS requests?

private boolean isExcluded(ServletRequest request) {
    return ((HttpServletRequest)request).getMethod().equalsIgnoreCase(HttpMethod.OPTIONS);
}

On doFilter:

if (this.isExcluded(request))
    chain.doFilter(request, response);
else
    //...

Is this correct?

Jordi
  • 20,868
  • 39
  • 149
  • 333

1 Answers1

3

Any CORS processing should be done before any auth. The correct way to implement it would be have a CORS filter before any auth filter. In the CORS filter, check if it is a preflight request. If it is, then respond with a 200 and set the CORS response headers. Then return from the filter so there is no further processing. If it isn't a preflight request, then just go to the next filter in the chain.

CORS filters only implemented on the response side and let the request go as usual are bad implementations. For example, my post here is a really bad example. That's why I linked to the RESTEasy CorsFilter as an example of how it should be implemented.

For more information about the CORS preflight, see the MDN (MUST read if you want to understand how it supposed to work). Then examine the RESTEasy CorsFilter to see how it is correctly implemented. Though it uses a JAX-RS filter, you can get some ideas for making it work with the servlet filter. The difference to note is that the JAX-RS filters are split into two filters (request and response), while servlet filters use on filter, where you pre-process -> handle request -> post-process. The JAX-RS filters are like the pre-process and post-process.

Also note that an OPTIONS request is not always a preflight. You should also check for the Origin header.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720