blak3r
blak3r

Reputation: 16516

Jquery .ajax fails when basic auth username has @ symbol (ios / cordova)

I have a phonegap app w/ jQuery 1.9.1 Worked great as long as the username doesn't have '@' symbol in it (like in email addresses). It only fails on iOS.

I suspect it's probably not urlencoding the @ sign or something.

Again works perfectly if username doesn't have an '@'

The reason I suspect it's something with url encoding is if it was posting it as: https://user@domain:[email protected], the browser wouldn't probably include the domain:password part as the host (since the first @ is what separates user:pass from the domain...

Here's what clued me in to this:

enter image description here

^-- I thought the entire point of base64 encoding was exactly to avoid special characters causing issues... so I thought that maybe this was chrome being helpful...

Related SO Posts: - Basic Authentication fails in cordova ios (no answers, slightly different)

Upvotes: 7

Views: 1575

Answers (3)

Steve K
Steve K

Reputation: 4921

When base64encoded text is UNencoded on the other end, it still looks like (as you said), user@domain:[email protected] Try having a function like this:

var getAuthToken = function (user, pass) {
    var token = "";
    if (user) {
        token = token + encodeURIComponent(user);
    }
    if (pass) {
        token = token + ":" + encodeURIComponent(pass);
    }
    token = $.base64.encode(token);
    return "Basic " + token;
};

Then just change your code slightly:

xhr.setRequestHeader("Authorization", getAuthToken(this.username, this.password));

Upvotes: 0

jrub
jrub

Reputation: 380

I would bet the problem is not using a contentType : "application/x-www-form-urlencoded".

Anyway, you should definitely debug your Webview against a real device, to look for xhr errors on the Safari console. If you are not familiar with Safari remote debugging, it's easy:

  • in your iPhone/iPad, go to Settings -> Safari -> Advanced => Enable Web Inspector.
  • connect to MacOSX via cable, and select your app from the "Develop" menu of Safari in your desktop
  • Now check any errors regarding your request, or better yet, debug the code and callbacks step by step.

Upvotes: 1

Markus Zeller
Markus Zeller

Reputation: 9090

Try wrapping encodeURIComponent() before base64 encoding.

beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization",
            "Basic " + $.base64.encode(encodeURIComponent(this.username + ":" + this.password)));
    },

Upvotes: 0

Related Questions