I am trying to create a basic authentication through the browser, but I can\'t really get there.
If this script won\'t be here the browser authentication will take o
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
The btoa function Base64 encodes a string.
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader
, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax
call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized
response, instead of setRequestHeader
(pre -1.7) use 'headers'
:
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw@domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},