December 25, 2014

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);
xml.open('GET',url)

// ExtJS
Ext.Ajax.request({
    url : url,
    method : 'GET',
    headers : { Authorization : auth }
});

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

[tags]ajax,javascript,extjs,xmlhttprequest,jquery[/tags]

Share and Enjoy:
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax
  • services sprite How to do HTTP Basic Auth in Ajax

Related posts:

  1. Ajax remoting for Invisible Castle I offer the code for my Invisible Castle site under...
  2. AJAX goodness for Invisible Castle I just rolled my first real AJAX application out to...
  3. Why I'm moving from jQuery to ExtJs Update (21 Nov 2008): I changed my mind a few...
  4. Enhancing FAQs with jQuery I’m so pleased by how useful and concise jQuery has...
  5. Simple, degradable Flash embedding using jQuery Now that I am doing professional web layouts for clients,...

About Bruce Kroeze

Comments

  1. alex says:

    How exciting! I hope you will share more of the process and the result, too! Cheers

  2. alex says:

    we have just noticed a slight bug on our end which seems relevant to what you are doing. The bug is fixed but we changed the headquarters url in the process. Check weewar.com/api for details. Cheers

  3. Bobby Jack says:

    Noticed a couple of bugs in the source here:

    o Call to “make_basic_auth”, function defined as “make_base_auth”

    o In that same function, reference to “pass” parameter, parameter is actually named “password”

  4. Arne says:

    good post, I adapted it for YUI, which I use in a a current project.

  5. marilyn says:

    Just curious if you had any trouble with the setRequestHeader() being called before open() in that AJAX call. It’s causing an error over here in Firefox, and nothing seems to be happening in IE…

  6. The XMLHttpRequest Object supports Basic Auth natively.

    xml = new XMLHttpRequest();
    xml.open(’GET’,url, true, username, password);

  7. Christoph says:

    Thx for the tutorial. I am writing a small weewar-tool too. While trying to get the login working i found a small bug in step 3.
    You need to execute xml.open() first an than user xml.setRequestHeader(). Otherwise you get an Error.

  8. Chad Woolley says:

    Nice post, thanks. This helped me.

  9. This was hugely helpful. Thanks!

  10. ivan says:

    function make_base_auth(user, password) {

    password => pass

    cheers, tnx

  11. Hans Brough says:

    useful for making requests of same something from the same domain … but if you are using a service API (like twitter) using xmlhhtprequest isn’t allowed because of the same domain security rule in JS.

    So… that brings to mind the script tag hack (otherwise known as JONP) but how to set the Authorization header in this case?

  12. Filip says:

    in jQuery you can add:
    password: ‘pass’,
    username: ‘name’
    no need for encoding and building headers.

    cheers

  13. Dexif says:

    Thanks for the idea!

  14. cristi says:

    I’m trying to use your authentication method for a json script :
    url = ‘http://interfaces-server.insource.local/users/145198/
    $.getJSON(url, function(data) {
    $(‘#info_title’).html(
    ” + “General Information ” + data.name + ”
    );
    });

    but i cant get it to work.

    i am using jquery

    thanks

  15. brownmamba says:

    Doesn’t work. The browser pops an authentication window as it receives a 401 from server. I’ve been trying to find a workaround for this for days now.

    p.s. I’m not saying what you’re doing is incorrect. It is. I’m just saying that it doesn’t work.

Speak Your Mind

*