guillaumeb
guillaumeb

Reputation: 161

Why my requests with http basic auth get status 0 when I set bad credentials ? Phonegap Android

In my android app made with phonegap, users can sign in. When they do it, JQuery get their login and their password and do an ajax call with theirs credentials following the HTTP Basic Auth specification. Everything works fine.
However I'm encountering a problem for handling the situation when a user sets bad credentials. In the .error() callback, I want to display a specific message for status 401 (like "authentication failed") and another message for other status ("technical problem"). My code :

$.ajax({
                url: "http://exemple.com",
                type: "GET",
                dataType: "text",
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                beforeSend: function (xhr)
                {
                    xhr.setRequestHeader("Authorization", "Basic "+$.base64.encode(email+":"+password));
                },
                success: function() {
                    //my success callback
                },
                error: function(xhr) {
                    if(xhr.status===401) {
                        //"authentication failed"
                    }
                    else {
                        //"technical problem"
                    }
                }
            });

This code works fine in browser. Status 401 is send. But when I test in my phonegap android app, the status send is 0. When my credentials are good, the status send is 200, and others requests of my app works well, so I don't think it's a cors problem.

Any idea ? Thanks for your help

Upvotes: 1

Views: 2991

Answers (2)

guillaumeb
guillaumeb

Reputation: 161

With more research, I understand that the problem comes from phonegap. The server respond to the ajax request with a status 401 and WWW-Authenticate : Basic realm="Secured Area" in the headers. WebView intercepts the response, and because of the header, waits for credentials. But this behavior is invisible on the phone so the request reaches the timeout and triggers a 0 status code.
One good solution is to change the response of the server to not include the WWW-Authenticate header. My solution, which is probably bad but quick, is to consider a 0 status as a 401 status.

error: function(xhr) {
                        if(xhr.status===401 || xhr.status===0) {
                            //'authentication failed'
                        }
                        else {
                            //'technical error'
                        }
                    }, 

Hope it can help someone.

Upvotes: 5

Rob
Rob

Reputation: 791

Funny. I've just recently run into the same issue, only I was passing the username and password attributes to .ajax instead of using beforeSend.

Try changing "$.base64.encode" to "btoa" https://developer.mozilla.org/en-US/docs/DOM/window.btoa.

Upvotes: 0

Related Questions