Reputation: 16516
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.
Android, works fine.
$.ajax({
url: "https://" + this.hostname + "/alertusmw/services/rest/" + endPoint,
type: method,
dataType: 'json',
contentType: 'application/com.alertus-v1.0+json',
cache:false,
username: this.username,
password: this.password,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + $.base64.encode(this.username + ":" + this.password));
},
data: options.data
}).done(function(response) {
console.log("DONE: " + method + ' completed: ');
console.log(response);
options.success( response );
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + method + " FAILED: " + textStatus + "\n" + "ERROR THROWN: " + errorThrown);
console.log("jqXHR thing: ", jqXHR);
options.error(jqXHR,textStatus,errorThrown);
})
.always(function(jqXHR, textStatus, errorThrown) {
console.log("In the always", jqXHR, textStatus, errorThrown);
});
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:
^-- 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
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
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:
Upvotes: 1
Reputation: 9090
Try wrapping encodeURIComponent() before base64 encoding.
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + $.base64.encode(encodeURIComponent(this.username + ":" + this.password)));
},
Upvotes: 0