Ajax authentication with jQuery

I can get the requested xml with

curl -X GET -u username:password url 

but not with

 $.get('url', {username:"username",password:"password"}, function (data) { }); 

No JavaScript errors, no cross-power issues. This may be a syntax error, but so far it has not been possible to find a worthy textbook. Any suggestions please?

+4
source share
3 answers

I think you need a simple format:

 $.ajax({ type: 'GET', url: 'url', dataType: 'json', //whatever you need beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', make_base_auth(user, password)); }, success: function () {}); }); function make_base_auth(user, password) { var tok = user + ':' + password; var hash = btoa(tok); return 'Basic ' + hash; } 
+20
source

As an alternative to beforeSend you can use the headers property to add an authorization header.

 $.ajax({ type: 'GET', url: 'url', dataType: 'json', headers: { "Authorization": make_base_auth(user, password) } success: function () {}); }); 
+2
source

As pointed out in another answer, you should use the sendSend JQuery Ajax function to add an authorization header

 function setAuthHeader(xhr){ var creds = username + ':' + password; var basicScheme = btoa(creds); var hashStr = "Basic "+basicScheme; xhr.setRequestHeader('Authorization', hashStr); } $.get('url', beforeSend: setAuthHeader, function (data) { }); 
+1
source

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


All Articles