How to add Basic Authentication to an AJAX call

I am creating a Phone Gap application that is using AJAX to “POST” information to my webserver. I would like to add Basic Authentication (username & password) to the http message so that my web service can authenticate the data beng sent. How do I add this to my AJAX call?

Much appreciate,
Robert

What do you have to far in terms of your AJAX call? Post your work file so others can have a look. Just don’t include sensitive info.

Are you using an REST API service or is it a straight post to page?

Basic post calls are all good but with mobile apps being stateless, you’d be hammering the server a lot if you make lots of requests. Also Basic Auth is not encrypted but encoded. Increase security and HTTPS it.

Look into JWT as it’s better for scaling.

Sorry for the few days of delay but I was busy with other concerns.
Here is some of the sample code at present…

Function btn_SN_TakePicture_onclick()
  Dim options = {quality : Number(gSettings.PhotoQuality), _
                 destinationType : 0, _
                 sourceType : 1, _
                 correctOrientation : True, _
                 saveToPhotoAlbum : False, _
                 allowEdit: False}
  
  navigator.camera.getPicture(onPictureReturned, onPictureError, options)
End Function

Function onPictureReturned(ImageData)
  Dim TimeStamp
  TimeStamp = FormatDateTime(Now, "YYYYMMDD") & "_"
  TimeStamp = TimeStamp & Right("00" & Hour(Now),2)
  TimeStamp = TimeStamp & Right("00" & Minute(Now),2)  
  TimeStamp = TimeStamp & Right("00" & Second(Now),2)
  
  gReq = Ajax("http://10.0.0.50:8080/SavePhoto?" & "Notice=" & gNotice.NoticeNo & "&TimeStamp= " & TimeStamp, "POST", ImageData, photoSent)
End Function

Function onPictureError(message)
  MsgBox "Photo Failed because: " & message
End Function

Function photoSent()
  Dim message
  If gReq.status = 200 Then 'success
    MsgBox "Photo uploaded!"
  Else 'failure
    message = "Error: Status = " & gReq.status
    If TypeName(gReq.statusText)="string" Then message = message & " " & gReq.statusText
    If TypeName(gReq.err)="string" Then message = message & " " & gReq.error
    MsgBox message
  End If
End Function

As you can see, I am using a straight POST to the WebService where I send the image in the message body and a couple of parameters in the URI.

I understand that Basic Authentication is not the same as using HTTPS security but my customer is not ready to implement HTTPS at this point in time. That is why I was asking about simple Basic Authentiction and how to add it to the AJAX call.

A few things here but I get what you’re trying to do I think.

It appears you’re using AppStudio’s AJAX wrapper. I usually go with jquery as it allows me more options. I’m not sure if it will allow you to send the auth info in the request headers as it was probably built to simplify the process.

I see that you are also sending your imagedata and most likely doing some processing with it as its encoded as base65… As such, if you are using some form of middleware, why not also pass the auth info in the query string to that endpoint (cringe)? Again, not how I would do it but you can also use some type of base64 encoding to pad it a bit as it would be sent as clear text.

Optionally, you can use $.ajax() method and send the basic auth info in the headers. That would allow you to specify the content type being sent.

But srsly, try to convince your client of getting https else make sure you indemnfiy yourself that you’ve done you diligence in letting them know of the security risk just in case that proverbial fan gets hit.

AppStudio’s Ajax() function is simply a wrapper for $.ajax(), to make it a bit more VB like. Either will work fine.

Let me echo @cayocoder about HTTPS. You’ll be doing client a favor by insisting on it. More than 80% of the internet is already on it.

If you’re interested, here’s what AppStudio’s Ajax function looks like:

function Ajax(URL, method, data, callback, errorCallback) {
	var settings;
	if (typeof (method) === 'function') {
		callback = method;
		data = "";
		method = "";
	}
    if (typeof (method) !== 'object') {
        settings = {};
        if (!method || method === null || typeof (method) === 'undefined') method = "GET";
        settings.type = method.toUpperCase();
        if (!data || data === null || typeof (data) === 'undefined') data = "";
        settings.data = data;
        if (!callback) {
            settings.async = false;
        } else {
            settings.success = callback;
            if(!errorCallback) errorCallback = callback;
            settings.error = errorCallback;
        }
    } else {
		settings = method;
	}
    return $.ajax(URL, settings);
}
1 Like

Sorry I meant base64 regarding the imagedata.

In jquery you can easily set the header like this:

  $.ajax({
      type: 'POST',
      url: "http://endpoint.domain.com",
      data: "var1=1&var2=2",
      headers: {"X-AUTH-TOKEN" : token},
      datatype: 'json',
      timeout: 5000,
      cache: false,
      beforeSend: function() {
         //Show spinner
         showSpinner();
      }                  
  }).done(function(data, textStatus, jqXHR) {
        // get the response here
        if(data.status == "OK")
        {
            // save new token for next call
            some_var = data.token
        }
  }).fail(function(xhr, textStatus, error) {
      ajaxError(xhr, textStatus, error, 1041);
  }).always(function(jqXHR, textStatus) {
      // hide spinner
      hideSpinner();
  });

And then in .php you can dump the headers like this:

print_r($_SERVER);
1 Like

Thank you all, for your code samples and the time that you took in helping me with my understanding. I will take your advise and get the customer on board with HTTPS (if they want the added security).

Cheers, and here’s to a wonderful Holiday Season and a properous New Year.