When is it safe to enable CORS? When is it safe to enable CORS? ajax ajax

When is it safe to enable CORS?


In answer to your second question (If a CORS enabled server sets a session_token through a cookie...?), the cookie is saved under the domain of the CORS server. The main web page's JS code can't access the cookie, even via document.cookie. The cookie is only sent to the server when the .withCredentials property is set, and even then, it is only accepted when the server sets the Access-Control-Allow-Credentials header.

Your first question is a little more open ended. It is fairly secure, but there are ways to circumvent things. For example, an attacker could use a DNS poisoning technique to cause a preflight request to hit the actual server, but send the actual CORS request to the rogue server. Here are some more resources on CORS security:

Lastly, your concern is around giving any website access to your CORS data. In order to protect against this, you should not use the Access-Control-Allow-Origin: * header. Instead, you should echo back the user's Origin value. For example:

Access-Control-Allow-Origin: http://www.example.com

This header will allow only http://www.example.com to access the response data.


The intention of CORS is to allow cross-origin requests for XHR requests while giving the server the authority to specify what origin has access to which resource. In particular, CORS introduced the Origin header field that allows the server to tell regular and possible XHR requests apart. This header field cannot be set or changed by the user but is set by the browser for XHR requests.

So if you have an API that is designed to be only used by XHR, you can (and should) require the request to conform with CORS. Especially if the requests can also modify state on your server as otherwise you would be vulnerable to CSRF.

Note the CSRF attacks are possible regardless of CORS using other methods to forge GET and POST requests. CORS does only enable to access the server’s response of XHR requests with JavaScript if the server allows it.