6

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);
},
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57
  • What makes you think the header is not set? Have you inspect the actual xhr call? Could either `Crypto`, `username` or `password` be set to `undefined`? You could also use curl and set the header (-H) and see if isn't a server side problem. BTW, I'm the one who wrote that blog post ;-) – pdeschen Jul 18 '12 at 18:37
  • I'm writing the xhr call to the log, what am I looking for within the object? I've checked and all 3 are defined correctly. What's currently happening is I'm getting a 401 unauthorised error for obvious reasons. That's good to know, good post. – Ryan Brodie Jul 19 '12 at 09:14
  • with Chrome, if you open the Developer Tools and you select the Network tab and then XHR element in the bottom list, you can inspect the actual ajax requests, its content, the headers and all. – pdeschen Jul 19 '12 at 20:26

2 Answers2

8

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> 
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57
0

This finally seems to work for me. There could be collisions on an individual call basis. Sets this method as a default for future connection options.

//Function( jqXHR jqXHR )
$.ajaxSetup( {beforeSend: function(jqXHR) {
    jqXHR.setRequestHeader( "My-Header", "My-Value" );
} } );
englebart
  • 563
  • 4
  • 9
  • 2
    It seems that `ajaxSetup` no longer exists, so I used `ajaxSend`: `$(document).ajaxSend(function(e, xhr, settings) { xhr.setRequestHeader("Authorization", "mytoken"); });`. See http://api.jquery.com/ajaxSend/ – falsarella Mar 09 '15 at 18:56