AngularJS trying to do CORS

I have a Ruby On rails Json API. I also have an AngularJS frontend and I am making CORS requests.

Everything works ok when I return 200 (for example on posts it's actually calling OPTIONS method and getting cors headers for the server). But when I return 401 (unauthorized) I get a Cross site error. I want to handle this error and show an appropiate message (when the user is not authorized to execute a method) but it seems that 401 response fires CORS error.

Any help?

CORS is independent of authentication. Your should layer your CORS response on top of your actual response. So in the case of an authentication error, here's how you should respond:

  1. The preflight response (e.g. the response to the OPTIONS request) should always return HTTP 200, along with the appropriate CORS headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers (if necessary). There should be no body on the preflight response.
  2. The actual response should respond with 401, if there is an auth error. But it should still have the CORS headers, e.g. Access-Control-Allow-Origin etc.

This tells the browser that the cross-origin request was successful, but there was an underlying issue with the request (e.g. the auth error).