Pre-emptive HTTP Basic Authentication with JQuery

In a previous post we looked at setting up basic auth with Spring, and how to call it with a Spring RestTemplate. In this post we will look at how to make an ajax call with JQuery using basic auth. This is a common enough scenario to warrant a popular StackOverflow question, so I thought it warranted a blog post.

The basic code is simple enough: add the appropriate request headers to pre-emptively send the auth information to the jquery request object without waiting for an initial response. In this snippet, request is an object that can be passed to $.ajax().

   request.headers = {
     "Authorization": "Basic " + btoa(credentials.username + ":" + credentials.password)

Next, we can also use an additional function that creates request objects that can be passed to $.ajax().

// this function creates request objects that can be passed to $.ajax()
var ajaxObjectMaker = function(httpMethod, url, requestBody, successCallback, failureCallback) {
   if(typeof(requestBody) !== 'string') {
      requestBody = JSON.stringify(requestBody);
   return {
      'contentType': 'application/json',
      'dataType': 'json',
      'type': httpMethod,
      'url': url,
      'data': requestBody,
      'success': successCallback,
      'error': failureCallback
var postJson = ajaxObjectMaker.curry('POST');
var putJson = ajaxObjectMaker.curry('PUT');
var getJson = ajaxObjectMaker.curry('GET');
var deleteJson = ajaxObjectMaker.curry('DELETE');

var addBasicAuth = function(request, username, password) {
   request.headers = {
     "Authorization": "Basic " + btoa(username + ":" + password)
   return request;

This allows us to compose functions as needed to more cleanly include the basic auth header or not. This is a bit cleaner than, say, using a flag to determine whether to add the auth information.

$.ajax(addBasicAuth(putJson(someObjectUrl, someJsonString, onPutObjectSuccess, onPutObjectFailure), username, password));

Happy Authenticating!

1 Comment

Filed under Software Engineering

One response to “Pre-emptive HTTP Basic Authentication with JQuery

  1. Nice post Jason, thanks. You might be interested in how to use HTTP Basic Auth with raw javascript XmlHttpRequest interface. See

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s