Use Basic Authentication With Jquery and Ajax

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



Leave a reply



Submit