Ajax:HTTP Basic Auth和身份验证cookie [英] Ajax: HTTP Basic Auth and authentication cookie

查看:796
本文介绍了Ajax:HTTP Basic Auth和身份验证cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将HTTP基本身份验证标题存储在身份验证cookie中,这样我就不必在后续请求中处理授权标头(我正在使用jQuery):

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):

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
    });
},

虽然这似乎适用于第一个登录的用户,但它没有不适用于浏览器会话中的任何其他用户,因为后续的授权标头已添加但未被覆盖。我知道可以使用 name = value 语法覆盖cookie,但此语法不适用于授权标头。

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.

新用户登录后有没有办法摆脱旧的授权标题?

Is there any way to get rid of the old authorization header once a new user logs in?

任何帮助都将不胜感激。谢谢,JeHo

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).

我现在正在做的是将登录信息存储在标准的name = value cookie中并手动设置授权标题。

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

设置cookie:

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

阅读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 "";
  }
}

设置授权标题:

    $.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.

这篇关于Ajax:HTTP Basic Auth和身份验证cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆