Charles Offenbacher
Charles Offenbacher

Reputation: 3132

jQuery not sending Authorization header

For some reason, this code is not sending the Authorization header. Why is that? Are there alternatives?

$.ajax({
      type: "POST",
      data: JSON.stringify(q),
      url: "https://elasticsearchinstance" + "/index/_search",
      contentType: 'application/json',
      crossDomain: true,
      dataType: 'json',
      processData: false, 
      headers: {
        "Authorization": "Basic " + btoa("username:password")
      },
      success: searchCallback
    });

401 Unauthorized

If I manually edit the request in Fiddler to add the Authorization header, I get HTTP 200.

Edit - including this also does not help:

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

Edit - username and password also have no effect:

username: "username",
password: "password"

Upvotes: 0

Views: 917

Answers (2)

Charles Offenbacher
Charles Offenbacher

Reputation: 3132

Ah - turns out my ElasticSearch instance had CORS disabled. As I understand it, Chrome insists on sending an OPTIONS request to see if cross-domain POST is allowed before sending the POST itself in order to protect the security of the browser user.

By manually modifying the request and adding the Authorization header in Fiddler, I was able to skip that. (Due to the browser's insistence on OPTIONS, no website would arbitrarily have the ability to do that via javascript, which is why I couldn't get the header added).

Upvotes: 1

pBuch
pBuch

Reputation: 1001

Why don't you use username and password instead of headers?

Upvotes: 0

Related Questions