9

I'm attempting to upload a file from PhoneGap to a server using the FileTransfer method. I need HTTP basic auth to be enabled for this upload.

Here's the relevant code:

    var options = new FileUploadOptions({
        fileKey: "file",
        params: {
            id: my_id,
            headers: { 'Authorization': _make_authstr() }
        }
    });
    var ft = new FileTransfer();
    ft.upload(image, 'http://locahost:8000/api/upload', success, error, options);

Looking over the PhoneGap source code it appears that I can specify the authorization header by including "headers" in the "params" list as I've done above:

      JSONObject headers = params.getJSONObject("headers");
      for (Iterator iter = headers.keys(); iter.hasNext();)
      {
        String headerKey = iter.next().toString();
        conn.setRequestProperty(headerKey, headers.getString(headerKey));
      }

However, this doesn't seem to actually add the header.

So: is there a way to do HTTP basic auth with PhoneGap's FileTransfer, for both iPhone and Android?

Parand
  • 102,950
  • 48
  • 151
  • 186
  • For anyone wondering, this method listed above works for me. Just need to add this: `params.headers = {Authorization: 'Basic ' + creds}; options.params = params;` – gabaum10 Jan 08 '13 at 20:36
  • headers need to go to options.headers not added to options.params.____ – Adam Jul 21 '14 at 22:53

3 Answers3

10

You can add custom headers by adding them to the options rather than the params like so:

authHeaderValue = function(username, password) {
    var tok = username + ':' + password;
    var hash = btoa(tok);
    return "Basic " + hash;
};

options.headers = {'Authorization': authHeaderValue('Bob', '1234') };
Ryan
  • 5,416
  • 1
  • 39
  • 36
  • FYI, I am having issues with this in iOS (as of 1/14/13). Works fine in Android and BB... – gabaum10 Jan 14 '13 at 14:34
  • what version of phonegap are you using? I have had success on iOS with 2.3.0 – Ryan Jan 14 '13 at 19:34
  • 2.2.0... that's interesting, perhaps I should try to upgrade? Were you having issues before with 2.2.0? – gabaum10 Jan 14 '13 at 20:28
  • yes, but I was also (incorrectly) placing the headers in the params as the OP was doing. – Ryan Jan 14 '13 at 20:45
  • Ohhh, I am doing that as well: `params.headers = {Authorization: 'Basic ' + loginCreds} ;` that's not right? – gabaum10 Jan 14 '13 at 21:00
  • FWIW, simply doing `options.headers = { 'Authorization' : 'bob:1234' }` does not work (at least for me. I had to follow the `"Basic " + btoa("bob:1234")` method. – Adam Jul 21 '14 at 23:03
0

The correct location for the headers array is as an immediate child of options. options->headers. Not options->params->headers. Here is an example:

//**************************************************************
//Variables used below:
//1 - image_name: contains the actual name of the image file.
//2 - token: contains authorization token. In my case, JWT.
//3 - UPLOAD_URL: URL to which the file will be uploaded.
//4 - image_full_path - Full path for the picture to be uploaded.
//***************************************************************
var options = {
  fileKey: "file",
  fileName: 'picture',
  chunkedMode: false,
  mimeType: "multipart/form-data",
  params : {'fileName': image_name}
};

var headers = {'Authorization':token};

//Here is the magic!
options.headers = headers;
//NOTE: I creaed a separate object for headers to better exemplify what
// is going on here. Obviously you can simply add the header entry
// directly to options object above.

$cordovaFileTransfer.upload(UPLOAD_URL, image_full_path, options).then(
   function(result) {
      //do whatever with the result here.
 });

Here is the official documentation: https://github.com/apache/cordova-plugin-file-transfer

0

You can create a authorization header yourself. But you can also enter the credentials in the url like this:

var username = "test", password = "pass";     
var uri = encodeURI("http://"+username + ':' + password +"@localhost:8000/api/upload");

See FileTransfer.js for the implementation (line 45):

function getBasicAuthHeader(urlString) {
var header =  null;


// This is changed due to MS Windows doesn't support credentials in http uris
// so we detect them by regexp and strip off from result url
// Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem

if (window.btoa) {
    var credentials = getUrlCredentials(urlString);
    if (credentials) {
        var authHeader = "Authorization";
        var authHeaderValue = "Basic " + window.btoa(credentials);

        header = {
            name : authHeader,
            value : authHeaderValue
        };
    }
}

return header;
}
Thieme
  • 294
  • 1
  • 13