NodeJS 如何解决JsonWebTokenError“无效签名”在分配一些信息给生成的令牌后?

7vux5j2d  于 2022-11-03  发布在  Node.js
关注(0)|答案(4)|浏览(281)

在尝试验证令牌时出现问题(在生成令牌之前,在我向令牌添加一些数据之前,令牌工作正常)..但现在它似乎不工作了!
这是当用户发送POST请求(登录)时我生成令牌的方式

require('dotenv')
const jwt       = require('jsonwebtoken');
const bcrypt    = require('bcryptjs')
const Role      = require('../models/Role');
const Section   = require('../models/Section');
const User      = require('../models/User');

// Login !
router.post('/', async (req, res) => {

    let sections_fetched = [];

    // Validate data 

    // Check username
    const user = await User.findOne({username: req.body.username });
    if(!user) return res.status(400).send('Wrong user login credentials !');

    // Check password
    const is_pass_valid = await bcrypt.compare(req.body.password , user.password);
    if (!is_pass_valid) return res.status(400).send('Wrong user login credentials !');

    // Get role Object:
    const _role = await Role.findOne({_id:user.role , is_deleted:false});
    if (!_role) res.json("Failed fetching role !");

    // loop through sections   
    for (let index = 0; index < _role.sections.length; index++) {

        const tmpRole = await Section.find({_id: _role.sections[index], is_deleted:false});
        sections_fetched.push({access:tmpRole[0].access , name:tmpRole[0].name});
    }

    // create jwt token
    const token = jwt.sign({username:user.username, role:{name:_role.name, sections:sections_fetched}}, 'secret', {expiresIn : '24h'}, process.env.JWT_TOKEN_SECRET);
    res.json({token:token});

});

这是我JWT验证中间件:

require('dotenv')
const jwt = require('jsonwebtoken');

module.exports = function (req, res, next) {

    const token = req.header('auth-token');

    if (!token) return res.status(401).send('Access Denied !');
    console.log(process.env.JWT_TOKEN_SECRET);
    console.log(token);

    try 
    {

        const verified = jwt.verify(token, process.env.JWT_TOKEN_SECRET);
        req.user = verified;  
        next();

    } 
    catch (error) 
    {
        res.status(400).send('Invalid token !');
    }
}

这是一个列出用户的简单示例(使用JWT验证中间件!):

const verifyToken = require('../middlewares/verifyToken'); // my jwt middleware to verify !

// Listing All users
router.get('/', verifyToken, async (req, res) => 
{
    try 
    { 
        const users = await User.find({is_deleted:false});
        res.json(users);
    }
    catch (error) 
    {
        console.log("err ->\n"+error);
        res.json({message: error});
    } 
});
kr98yfug

kr98yfug1#

什么是'secret在这下面的行?似乎你是添加一个秘密密钥两次,替换这硬编码的字'secret'与令牌从env

const token = jwt.sign({username:user.username, role:{name:_role.name, sections:sections_fetched}}, 'secret', {expiresIn : '24h'}, process.env.JWT_TOKEN_SECRET);
yjghlzjz

yjghlzjz2#

发送一个不记名令牌,您的中间件应该会喜欢它

require('dotenv')
const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN'
    if (!token) {
      throw new Error('Authentication failed!');
    }
    const verified = jwt.verify(token, process.env.JWT_TOKEN_SECRET);
    req.user = verified;  
    next();
  } catch (err) {
    res.status(400).send('Invalid token !');
  }
};

niwlg2el

niwlg2el3#

请确保在生成令牌时传递了一个有效的算法。我将算法存储在一个环境变量中,但使用的是无效的none算法。因此,即使创建了令牌,我也无法使用相同的密钥对其进行验证。我花了几个小时来尝试修复此问题。我希望这对您有所帮助:D

sign(payload, JWT_SECRET, {
    algorithm: JWT_ALGORITHM,
    expiresIn: '1d'
});
6mzjoqzu

6mzjoqzu4#

用于验证:

jwt.verify(req,'SecretKey', function (err, res) {
      if (err) {
        callback(res);
      } else {
        callback(res);
      }
    });

签名:

jwt.sign({username:user.username, role:{name:_role.name, sections:sections_fetched}}, 'secret', {expiresIn : '24h'}, process.env.JWT_TOKEN_SECRET,function(err,res){
    if (err) {
        callback(res);
      } else {
        callback(res);
      }});

相关问题