首页 > 解决方案 > 无法将 JWT 分配给标头请求

问题描述

我在使用 JWT 时遇到问题。在负责登录页面的路由器中,在发布请求中,我为每个登录用户分配了一个 JWT,尽管我无法在每个页面请求的标头中发送令牌,也无法将令牌实际保存在标头中。当我在每次登录后控制台记录令牌并将其复制粘贴到 POSTMAN 的标题时,它工作正常,因此我认为这是我的问题;

// generate a jwt for the login user
   const token = jwt.sign({_id: this._id, isAdmin: this.isAdmin}, process.env.TOKEN_SECRET, 
   {expiresIn: 1800});

// send back to the homepage with the token in the header (?)
    res.header('auth-token', token).redirect('/');
    console.log(token);

在这个分配之后,我试图访问一个经过身份验证的用户页面,但它没有工作,我想是因为我提到的原因。

这是我的身份验证中间件,负责我添加到路由器的身份验证:

const jwt = require('jsonwebtoken');

module.exports = function(req, res, next) {
    const token = req.header('auth-token');
    if(!token){
        console.log('Access denied. No token provided.');
        return res.status(401).redirect('/login');
    }
    try{
        const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
        console.log(decoded);
        req.user = decoded;
        console.log('Access approved.');
        next();
    }
    catch(ex){
        console.log('Invalid token');
        res.status(403).redirect('/');
    }
}

我不知道我错过了什么。试图找到解决方案,但对我没有任何帮助。感谢帮助者!

标签: node.jsjwt

解决方案


推荐阅读