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

不想你离开。 提交于 2019-11-30 14:03:09

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.

Try wrapping encodeURIComponent() before base64 encoding.

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

When base64encoded text is UNencoded on the other end, it still looks like (as you said), user@domain:password@blah.domain.com 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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!