Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load basic auth secured images in phonegap app

I have a phonegap application that communicates with a web api that is secured using HTTP Basic Auth. The api returns html with img tags, which reference images that are also on the secured server. Somehow I need my app to be able to request and load these images. Injecting the basic auth credentials into the src (i.e. src=http://username:[email protected]/...) will not work. Also I do not control the server so I cannot send the images in base64.

My current approach is to request the images with $.ajax, setting the Authorization header, and then load the images to the DOM from the cache (since the images are cached by the ajax call). Ideally I should be able to request each image once with $.ajax, and then load the image from cache onto the page. This approach works if the page is reloaded (because the images are already cached) but will not load the images the first time that the request is made (even though I'm waiting for the request to complete). Note that my phonegap app only has one page (from an html DOM standpoint) on which content is dynamically loaded and unloaded, so the main page is never reloaded. Here is what I am currently trying:

$.ajax({
       url: 'http://MySecuredServer.com/images/example.png',
       beforeSend: function(req){
           req.setHeader('Authorization', 'Basic ' + base64UserCredentials);
       },
       cache: true,
       complete: function(){
            var img = document.createElement('img');
            img.src = 'http://MySecuredServer.com/images/example.png';
            $('#target').append(img);
       }
       });

I have also tried things like

complete: function(){
    var img = new Image();
    img.src = http://.....
    $(img).on('load', function(){
          $('#target').append(img);
    });
}

So here is the question: how can I get the secured images into my application? Is this the right approach, and if so, what am I doing wrong? If not, then how can I request these secured images? Any help with the general concept or the specific scenario would be really great. Thanks in advance!

like image 201
Uncharted Space Avatar asked Nov 04 '22 08:11

Uncharted Space


1 Answers

I ended up converting the binary data to base64 using NiKo's solution provided here and just setting the Auth credentials in the header.

//request image
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader('Authorization', 'Basic ' + encodedCredentials);
xhr.onload = function(e) {
    $("#target").attr('src', 'data:' + type + ';base64,' + base64ArrayBuffer(e.currentTarget.response));
};
xhr.send();

Where base64ArrayBuffer is the function given by NiKo.

like image 67
Uncharted Space Avatar answered Nov 08 '22 03:11

Uncharted Space