繁体   English   中英

如何将 jwt 令牌从 web 浏览器上的本地存储传输到服务器后端?

[英]How do I transfer a jwt token from local storage on the web browser to the server backend?

我目前正在设计一个简单的网站,用户可以在其中以普通用户或管理员身份登录。 Right now I am coding out the portion for when the user wants to go to an admin only web page, and the server will retrieve the jwt token stored in the local storage on the web browser to validate it.

Web浏览器的本地存储

这就是本地存储的样子

这是检索 jwt 令牌的代码

var verifyFn = {
verifyToken: function (req, res, next) {
    const authHeader = localStorage.getItem("jwt_token");
    console.log("THIS IS THE HEADER")
    console.log(authHeader)
    
    if (authHeader === null || authHeader === undefined ){
    return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' });
    }

    const token = authHeader
    console.log("NEW TOKEN")
    console.log(token)
    jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => {
        if (err) return res.status(401).send({ message: 'not authenticated' });
        req.decodedToken = decoded;
        console.log("DECODED TOKEN: " + req.decodedToken)
        next();
    });
}

但是,每当我尝试运行服务器并浏览到管理页面时,都会出现错误提示“未定义本地存储”。 因此,我不确定如何将 jwt_token 从 web 浏览器检索到服务器后端。

服务器无法访问浏览器的localStorage object,因为它只能从客户端访问,并且不存在于服务器上下文中。

通常所做的是在Authorization header 中发送令牌。 看起来您正在使用Node ,因此请考虑使用客户端上的 fetch API 的以下示例请求:

 const jwtToken = localStorage.getItem('jwt_token') fetch('your-api-url', { method: 'request method here', headers: { Authorization: `Bearer ${jwtToken}` }, body: JSON.stringify(your request body here) }).then(response =>...)

在服务器中,您可以通过查看响应标头来获取 JWT 令牌,如下所示:

 var verifyFn = { verifyToken: function (req, res, next) { let authHeader = req.headers['Authorization'] // the auth header will have Bearer prepended, so remove it authHeader = authHeader.replace('Bearer ', '') console.log("THIS IS THE HEADER") console.log(authHeader) if (authHeader === null || authHeader === undefined ){ return res.status(401).send({ message: 'not authenticated BEARER TOKEN ISSUE' }); } const token = authHeader console.log("NEW TOKEN") console.log(token) jwt.verify(token, config.jwt.secret, { algorithms: ['HS256'] }, (err, decoded) => { if (err) return res.status(401).send({ message: 'not authenticated' }); req.decodedToken = decoded; console.log("DECODED TOKEN: " + req.decodedToken) next(); }); }

暂无
暂无

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

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