How to do HTTP Basic Auth in Ajax

You can use HTTP Basic Authentication with Javascript/Ajax in just three steps. I’ll give you them in just a moment.

The Background

This morning, I was experimenting with Adobe AIR, writing a client to tell me whether I have games waiting for me to make a move on Weewar, and I needed to be able to use my username and “token” via Basic Auth to do that.

It was not easy to find how to do it. In fact, I had to connect a few dots to get it to work. Here you go:

Step 1

First, get Base64.js from Webtoolkit, and load it on your page. We need the encode routine from that library.

Step 2

Construct your Authorization header like so:

function make_base_auth(user, password) {
  var tok = user + ':' + pass;
  var hash = Base64.encode(tok);
  return "Basic " + hash;

Step 3

Use it in your Ajax call.

var auth = make_basic_auth('me','mypassword');
var url = '';

// RAW
xml = new XMLHttpRequest();
xml.setRequestHeader('Authorization', auth);'GET',url)

// ExtJS
    url : url,
    method : 'GET',
    headers : { Authorization : auth }

// jQuery
    url : url,
    method : 'GET',
    beforeSend : function(req) {
        req.setRequestHeader('Authorization', auth);