我想将 HTTP 基本身份验证 header 存储在身份验证 cookie 中,这样我就不必在后续请求中处理授权 header (我使用的是 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
});
},
虽然这似乎适用于第一个登录的用户,但它不适用于浏览器 session 中的任何其他用户,因为后续的授权 header 是添加的而不是被覆盖。我知道可以使用 name=value
语法覆盖 cookie,但此语法不适用于授权 header 。
有什么方法可以在新用户登录后删除旧的授权 header ?
如有任何帮助,我们将不胜感激。谢谢,JeHo
最佳答案
看来,它对第一个用户也不起作用。问题是,授权 header 可能是由浏览器早些时候设置的(当我使用浏览器的身份验证对话框时)。
我现在正在做的是将登录信息存储在标准名称=值 cookie 中并手动设置授权 header 。
设置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 "";
}
}
设置授权 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
});
这看起来有点尴尬,但它确实有效。
警告:确保对存储在 cookie 中的任何敏感数据进行编码,否则会导致安全问题。检查CWE了解更多信息。
关于javascript - Ajax : HTTP Basic Auth and authentication cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2455492/