HomeProgrammingHow to do HTTP Basic Auth in Ajax

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 = 'http://example.com';

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

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

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

I started out going to college for Business administration but soon found out that Coding would be a great way to have a sustainable career! I made coder's eye as my personal journey on learning how to code and sharing my Findings along the way. My vision with CE now is to be a way to help beginners that want to learn code but don't know where to start.


Sorry, the comment form is closed at this time.