XMLHttpRequest fails basic authentication
Asked Answered
W

2

6

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.

Wane answered 14/6, 2014 at 4:1 Comment(3)
Downvoters unite :) or at least 'splain yourselves. Is it "what havr you tried" ? Or "show your effort/code"? I will gladly listen.Wane
@JakeGould unfortunately it doesn't apply to me. JS part of Pebble app work correctly on iOS already. And always fails in Android Pebble JS framework - even with correct credentialsWane
@JakeGould this code runs not inside of WebView I don't think it applies either.Wane
W
17

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://mcmap.net/q/42154/-how-can-you-encode-a-string-to-base64-in-javascript) – and it worked! Perhaps there’s a bug in XmlHttpRequest implementation on android.

Wane answered 14/6, 2014 at 23:14 Comment(2)
Why not try btoa? is javascript pure.. ¬.¬ a try req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));Vicennial
btoa is ASCII onlyFroebel
D
0

If the request is authenticated via cookie/headers, we can set headers and make that request withCredentials value as false.

withCredentials attribute must to false in IOS otherwise, you may be getting 401 responses from the server.

Note:- In Android and web platforms works without 'withCredentials' property also

 req.open(method, fullurl, true);
 req.setRequestHeader("Cookie", "CookieInfo")); 
 req.send(data);    
 request.withCredentials = false;
Dysentery answered 14/9, 2023 at 7:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.