XMLHttpRequest fails basic authentication

Yuriy Galanter picture Yuriy Galanter · Jun 14, 2014 · Viewed 18.5k times · Source

Any idea why XMLHttpRequest with correct credentials in Pebble JS Framework fails basic authentication on Android but works in iOS?

Exactly the same code, along the lines of:

var req = new XMLHttpRequest();
req.open(method, url, true, user, pass);
req.send(data);
req.onreadystatechange = function() { ... }

Returns 401 in from Android Pebble app, but authenticates correctly in iOS.

Answer

Yuriy Galanter picture Yuriy Galanter · Jun 15, 2014

I found a workaround that worked for me on Android.

Don’t know why but direct authenticated request:

    req.open(method, fullurl, true, user, pass);
    req.send(data);

didn’t work for me – it always returned 401. So Instead I tried to set basic authentication via header:

    req.open(method, fullurl, true);
    req.setRequestHeader("Authorization", "Basic " + Base64.encode(user + ":" + pass)); 
    req.send(data);

(where Base64 is taken from here: https://stackoverflow.com/a/246813/961695) – and it worked! Perhaps there’s a bug in XmlHttpRequest implementation on android.