Cross Domain Request with Header Authentication

I need to send a Get request with a cross domain with header authentication.

Works fine in Chrome and Firefox, but I have problems with Safari and IE. Also in random cases, it returns 401.

 <script> var url = 'username: password@anotherdomain.com '; $.ajax({ url: url, dataType: 'jsonp', jsonpCallback: "callback", success: function(json) { alert(json); } }); </script> 

What would be the best option to solve this problem?

+3
source share
4 answers

If I understand the question correctly, you can use the beforeSend callback to add basic authentication to the request. It doesn't matter jsonp or cross-origin, though.

 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); } 

https://jsfiddle.net/rn9Lp304/

+2
source

For Internet Explorer 8 and 9 you need to use the XDomainRequest Object

Internet Explorer 10 + whether cross domain requests like all other browsers.

As mentioned in the documentation, you need to

  • create an XDR object with var xdr = new XDomainRequest();
  • open the connection using the get method using xdr.open("get", "username: password@anotherdomain.com ");
  • send data to the server using xdr.send();

A full link to the code can be shown as this @Mark Pieszak thread

as a workaround for setting username and password in Internet Explorer, you can set the following

DWORD for iexplore.exe to 0 in: [HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE] .

+1
source

I will recommend you try two things:

In ajaxSetup do the following:

 $.ajaxSetup({ ...., xhrFields: { withCredentials: true }, crossDomain: true, .... }); 

In your ajax requests, specify the full URL, for example, in addition to the credential flag.

 'Access-Control-Allow-Origin: https://not-example.com' 'Access-Control-Allow-Credentials: true' 

For authenticated servers, these browsers do not allow "*" in this header. The Access-Control-Allow-Origin header must contain the value of the Origin header sent by the client.

0
source

use getJSON

 $.getJSON("url",function (data) {/*code here*/}); 
-2
source

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


All Articles