Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX Header Authorisation

I'm trying to authorise an AJAX query based on this tutorial. It sets the request headers before send with the appropriate authorisation information by using the Crypto library. The problem I'm having is that headers don't seem to be set on request. Here's my code:

beforeSend : function(xhr) {
  var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
  var base64 = Crypto.util.bytesToBase64(bytes);
  xhr.setRequestHeader("Authorization", "Basic " + base64);
},
like image 973
Ryan Brodie Avatar asked Jul 18 '12 11:07

Ryan Brodie


People also ask

What is authorization request header?

The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.

What is request header in Ajax?

The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.


1 Answers

The issue was not setting the dataType to JSONP. As this was not done the browser interpreted the call as a standard AJAX request which meant it was being blocked under same-origin-policy.

Working code for reference (credit goes to @pdeschen for suggesting Crpyto):

<script type='text/javascript'>
// define vars
var username = '';
var password = '';
var url = '';

// ajax call
$.ajax({
    url: url,
    dataType : 'jsonp',
    beforeSend : function(xhr) {
      // generate base 64 string from username + password
      var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
      var base64 = Crypto.util.bytesToBase64(bytes);
      // set header
      xhr.setRequestHeader("Authorization", "Basic " + base64);
    },
    error : function() {
      // error handler
    },
    success: function(data) {
        // success handler
    }
});
</script> 
like image 154
Ryan Brodie Avatar answered Sep 18 '22 00:09

Ryan Brodie