CORS and Authentication

Let’s say that you have an API which stands on and you have a Javascript application that consuming this API from For to consume the API, has to send CORS header Access-Control-Allow-Origin in its response.

The simplest way to do this in Spring is annotate whole controller or just handler method with the annotation CrossOrigin.

It’s all what you need when your API does not require authentication.

On the other hand, when your API requires authentication, things get a bit complicated. For example, let’s say that you authenticate your API with HTTP Basic Authentication. So, consumers of this API must send an Authorization header which contains user credentials in their request. Since this is a non-simple request, OPTIONS request will be send firstly. The thing is that, even if you send Authorization header with correct credentials in your request, you will face something like below:


The reason of this is, according to CORS spec, it excludes your Authorization header. Hence, you should permit OPTIONS requests in your security configuration class explicitly.

Last of all, I suggest you to read these two posts: