javascript - 在 header 中传递访问 token 并在JavaScript中进行重定向

标签 javascript node.js jwt token

我正在尝试使用node.js实现基于 token 的身份验证。 token 生成正在运行。当用户登录时, token 被保存在浏览器cookie中。我的问题是我可以通过服务器上的node.js从cookie中读取 token ,因为它随每个请求传递,但据我所知,将 header 中的 token 作为x-access-token传递是一种更好的做法而且我不知道是否可以通过简单的页面加载来实现。

例如,当我登录时,获取并保存 token ,但之后应将我重定向到 protected 位置(例如,通过window.open(“/ protected”,“_self”)),并且无法设置此 header 请求。

我用于登录的JavaScript代码:

var httpRequest = new XMLHttpRequest();
var params = 'username=' + username.value + '&password=' + password.value;

httpRequest.open('POST', '/login', true);
httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httpRequest.responseType = "json";

httpRequest.onreadystatechange = function() {
        if(httpRequest.readyState == 4 && httpRequest.status == 200) {
            if(httpRequest.response.success){
                setCookie("loginToken", httpRequest.response.token, 1);
                window.open("/protected/", "_self");
            }
            showToast();
        }
}
httpRequest.send(params);

打开/ protected时,Node.js正在使用cookie解析器从cookie中读取 token :
var token = req.cookies.loginToken;

整个工作正常,但 header 中没有Cookie,但没有 token 。我应该使用cookie方法吗?如果没有,是否可以通过方法传递给 header 中的 token ?

最佳答案

用户登录时,不要使用cookie方法,而是将 token 存储在与user_id对应的数据库中的user_table中的 token 中,并检查 token 是否有效,然后允许用户进行任何 Activity ;否则,如果 token 无效,则注销用户并在注销时删除 token 。

关于javascript - 在 header 中传递访问 token 并在JavaScript中进行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967365/

相关文章:

javascript - 为什么requirejs允许指定字符串id?

javascript - 图像上传和预览选项,代码不允许显示不同的图像

javascript - 解决对象数组的 Bluebird promise

ios - 从服务器监听 iCal 事件变化

android - Facebook、Twitter 和 Instagram 等应用程序如何避免用户重新登录应用程序?

laravel - 处理 laravel 中的 jwt auth 错误

javascript - 如何将事件数据和 id 传递给 javascript 函数

javascript - 如何通过按键对按钮激活应用 CSS 效果?

android - socket.io - 无法在 Android 客户端中接收 "next(new Error())"事件?

jwt - 如果两个 JWT 的声明/ header 的顺序不同,它们是否仍应被视为相等?