简体   繁体   English

Ajax:HTTP 基本身份验证和身份验证 cookie

[英]Ajax: HTTP Basic Auth and authentication cookie

I want to store the HTTP basic authentication headerline in an authentication cookie, so that I don't have to deal with the authorisation header in subsequent requests (I'm using jQuery):我想将 HTTP 基本身份验证标头存储在身份验证 cookie 中,这样我就不必在后续请求中处理授权标头(我使用的是 jQuery):

authenticate: function(auth) {
    var header = "Basic " + $.base64.encode(auth.username + ":" + auth.password);
    document.cookie = "Authorization: " + header;
    $.ajax({
        type: "GET",
        url: "http://someurl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: auth.success,
        error: auth.error
    });
},

Whilst this seems to work for the first user who logs in, it doesn't work for any other users within the browser session, because the subsequent authorisation headers are added and not overwritten.虽然这似乎适用于第一个登录的用户,但它不适用于浏览器会话中的任何其他用户,因为随后的授权标头被添加而不是被覆盖。 I know that one could overwrite a cookie by using the name=value syntax, but this syntax does not apply to the authorization header.我知道可以使用name=value语法覆盖 cookie,但此语法不适用于授权标头。

Is there any way to get rid of the old authorization header once a new user logs in?一旦新用户登录,有没有办法摆脱旧的授权标头?

Any help would be appreciated.任何帮助,将不胜感激。 Thanks, JeHo谢谢,杰霍

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.我现在正在做的是将登录信息存储在标准的 name=value cookie 中并手动设置授权标头。

Set the cookie:设置cookie:

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

Read the cookie:读取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.这看起来有点尴尬,但它确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM