Use basic authentication with jQuery and Ajax
Use jQuery's beforeSend
callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
Ajax authentication with jQuery
I think you'd need the plain 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;
}
Basic authentication with jQuery ajax making two requests
Cross-site requests follow certain rules for security. A simple, single request can be made if the only custom headers set are:
- Accept
- Accept-Language
- Content-Language
- Content-Type
and the content type is one of:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
You are sending the Authorization
header and requesting HTML, so by default that requires a "pre-flight request":
Unlike simple requests, "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.
The initial OPTIONS
request without Authorization
is safe because the server only needs to respond with Access-Control-*
headers that let the browser know if your full request is OK to proceed. Then your actual request with Authorization
is going through, so everything is working as expected.
The XMLHttpRequest object does let you specify you're sending a request with credentials and possibly switch to just one request:
xhrFields: { withCredentials: true }
Related Topics
Modifying a Copy of a JavaScript Object Is Causing the Original Object to Change
How to Detect Idle Time in JavaScript
Executing ≪Script≫ Elements Inserted With .Innerhtml
How to Get a Subset of a JavaScript Object'S Properties
Why Does Changing an Array in JavaScript Affect Copies of the Array
How to Detect If Multiple Keys Are Pressed At Once Using JavaScript
How to Pass Props to {This.Props.Children}
Should All Jquery Events Be Bound to $(Document)
How Does "This" Keyword Work Within a Function
JavaScript Get Clipboard Data on Paste Event (Cross Browser)
Asp.Net MVC Jsonresult Date Format
How to Check If an Element Is Hidden in Jquery
How to Export JavaScript Array Info to CSV (On Client Side)
How to Retrieve Get Parameters from JavaScript
Question Mark and Colon in JavaScript