javascript - 保存简单的 Http 身份验证凭据以供以后使用
问题描述
我正在尝试一些关于简单http身份验证的事情,我创建了一个登录页面,我正在使用这个javascript函数从服务器请求一个受保护的页面,我正在接收http 200,我成功接收到我想要的页面的内容。问题是在我收到 http 200 之后,如果我想去另一个受保护的页面浏览器要求提供凭据。我不想在每次页面更改时都输入凭据。
如果我不使用我的登录页面,而是直接将受保护的 url 输入到浏览器,然后将我的凭据输入到浏览器的表单中:我可以浏览其他页面而无需每次都输入凭据。
function login()
{
var username = document.getElementById("UsernameInput").value;
var password = document.getElementById("PasswordInput").value;
var authorizationBasic = window.btoa(username + ':' + password);
var request = new XMLHttpRequest();
request.open("GET", "protected/mainPageEN.html", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'html');
request.send();
request.onreadystatechange = function ()
{
if(request.readyState == 0) //Request not initialized
{
alert("Not initializes");
}
else if(request.readyState == 1) //Server connection established
{
alert("Server connection established");
}
else if(request.readyState == 2) //Request received.
{
alert("Request received.");
}
else if(request.readyState == 3) //Processing request
{
alert("Processing request");
}
else if(request.readyState == 4) //Done
{
if(request.status == 200) //OK
{
alert(window.location.hostname);
//Set cookie
var header = "Basic " + authorizationBasic;
document.cookie = "Authorization=" + header;
window.location = "http://" + window.location.hostname + "/protected/mainPageEN.html";
}
else if(request.status == 403) //Forbidden
{
alert(request.statusText);
alert("Forbidden");
}
else if(request.status == 404) //Not found
{
alert(request.statusText);
alert("Not Found");
}
else
{
alert(request.status);
alert(request.statusText);
}
}
};
}
解决方案
看起来您的项目中需要某种身份验证机制。保存凭据以供以后使用是非常危险的,不推荐。由于您没有提到您正在使用的服务器端编程语言,因此无法推荐使用什么。但是,您必须在服务器端编程语言/框架旁边对该领域进行一些研究。
假设你想在客户端临时保存一些不敏感的东西,你可以使用 cookie、localstorage 或 webstorage。
Cookies - Cookies 是网站存储在您计算机上的一小段信息。Cookie 只包含一些文本,而不包含其他任何内容。文本可以是用户 ID、会话 ID 或任何其他文本。阅读更多
sessionStorage - 为页面会话期间可用的每个给定源维护一个单独的存储区域(只要浏览器处于打开状态,包括页面重新加载和恢复)。阅读更多
localStorage - 只读的 localStorage 属性允许您访问文档来源的存储对象;存储的数据跨浏览器会话保存。localStorage 与 sessionStorage 类似,不同之处在于,虽然 localStorage 中存储的数据没有过期时间,但 sessionStorage 中存储的数据会在页面会话结束时(即页面关闭时)被清除。阅读更多
还值得检查浏览器兼容性以及各种不同浏览器支持的这些存储的最大大小。
我希望这会有所帮助,谢谢。
推荐阅读
- ansible - Jinja2 模板中的相对路径
- tfs - TFS 用户组未更新
- php - Laradock 安装 msodbcsql
- python - 连接多个 DataFrame 列并删除多个空格
- java - 如何在 Kotlin DSL 中动态加载 TeamCity 子项目
- html - Angular 2 SVG在使用路由器时不会加载,刷新页面,它会呈现
- ios - Xamarin.Forms 任务与目标不匹配
- python - 如何比较python中的两个字典并相应地替换值?
- acumatica - Acumatica 视图插入抱怨客户管理首选项表单上的配置数据
- database - 无论架构更改如何,都自动传输数据