user2915883
user2915883

Reputation: 1

Use of basic authorization in JQuery ajax

I am creating an ajax call as follows:

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

The resultant HTTP request header contains

Access-Control-Request-Headers: authorization

When I issue the same request from the browser directly the request header correctly contains

Authorization: Basic ZG<etc>

Looking at the JQuery routines, jquery-1.20.2, the setRequestHeader is correctly adding the header name and value pair to the cached list of headers.

The AJAX call throws an error as a result of the authorization failing. (ZGetcetc matches what I see in the successful manual attempt)

Upvotes: 0

Views: 531

Answers (1)

Latheesan
Latheesan

Reputation: 24116

I am not sure if this is a viable option for you; upgrade your jQuery.

Newever jQuery has the ability to pass the basic auth username and password as part of the ajax call, e.g.

$.ajax
({
  type: "GET",
  url: "index.php",
  dataType: 'json',
  async: false,
  username: "YOUR-USERNAME-HERE",
  password: "YOUR-PASSWORD-HERE",
  data: '{ "DATA-HERE" }',
  success: function (data) {
     // handle success data
  }
});

Src: http://api.jquery.com/jQuery.ajax/


Another option:

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

Upvotes: 2

Related Questions