How to make a GET CORS request with an authorization header

I read about CORS requests and I managed to make a regular GET or POST request and it works fine. But when I add the authorization header to the GET or POST request, then the pre-check request request is sent to the server, and I get 500 ERR SERVER VERSIONS and the actual request is not sent. My question is how does preflight work, and what answer is required for it to send the main request? And is it possible to send it without pre-flight, because I am sure that then it will work? The rside service is written in Django 1.6 and has an ACCESS-ALLOW-ORIGIN value set to * and it works with regular mail and receives requests.

This is my JS code:

$.ajax({ type: "GET", url: "http://url/login/", async:false, contentType: "application/json", headers: { "Authorization": "Basic " + btoa(loginName + ':' + password), }, success: function (data) { alert("OK!"); }, failure: function(errMsg) { alert(errMsg); } }); 

These are the headers from Chrome DevTools when the request is executed: Request headers:

 OPTIONS /login/ HTTP/1.1 Host: url Connection: keep-alive Access-Control-Request-Method: GET Origin: null User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 Access-Control-Request-Headers: accept, authorization, content-type Accept: */* Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,hr;q=0.6,sr;q=0.4 

Answer headers:

 HTTP/1.1 500 INTERNAL SERVER ERROR Date: Thu, 31 Jul 2014 16:15:19 GMT Server: Apache/2.2.15 (CentOS) X-Frame-Options: SAMEORIGIN Access-Control-Allow-Origin: * Connection: close Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 
+6
source share
1 answer

To pass authorization headers, you must set Access-Control-Allow-Credentials to true.

The problem is that according to the specification ( MDN explains this easier ), if Access-Control-Allow-Credentials set to true, Access-Control-Allow-Origin cannot contain * , which allows any hosts to make requests with attached credentials.

There are two options for solving this problem:

  • Set Access-Control-Allow-Origin Current Host Requests
  • If there are several hosts: the "canonical" way would be to have a white list of hosts in the application itself than the Origin header if it is included in the list and adds the Origin value as Access-Control-Allow-Origin .

With Django, check out Origin and add a title to Middleware, but that would create a decent question (and might have already been asked)

+10
source

Source: https://habr.com/ru/post/973178/


All Articles