Ajax: HTTP Basic Auth and authentication cookie

余生长醉 提交于 2019-12-02 22:59:52
Jeldrik

It seems, that it didn't work for the first user either. The problem was, that the authorization header was probably set by the browser earlier on (when I used the authentication dialog of the browser).

What I'm doing now is storing the login information in a standard name=value cookie and setting the authorization header manually.

Set the cookie:

var header = "Basic " + $.base64.encode(auth.username + ":" + auth.password);
document.cookie = "Authorization=" + header;

Read the cookie:

function getAuthCookie() {
   var cn = "Authorization=";
   var idx = document.cookie.indexOf(cn)

   if (idx != -1) {
       var end = document.cookie.indexOf(";", idx + 1);
       if (end == -1) end = document.cookie.length;
       return unescape(document.cookie.substring(idx + cn.length, end));
   } else {
       return "";
  }
}

Set the authorization header:

    $.ajax({
        type: "GET",
        url: "http://someurl",
        contentType: "application/json; charset=utf-8",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Authorization", getAuthCookie());
        },
        dataType: "json",
        success: auth.success,
        error: auth.error
    });

This seems a bit awkward, but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!