【问题标题】:Payload error in jsonwebtokenjsonwebtoken 中的有效负载错误
【发布时间】:2018-04-17 11:32:04
【问题描述】:

我正在使用 nodejs 和 angular cli 制作一个 Web 应用程序 我正在使用 JWT 来验证我的登录功能。但是当我处理它时抛出了这个错误

错误:预期的“有效负载”是一个普通对象。 验证时 (D:\Mean_Projects\meanauthapp\node_modules\jsonwebtoken\sign.js:34:11) 在 validatePayload (D:\Mean_Projects\meanauthapp\node_modules\jsonwebtoken\sign.js:56:10) 在 Object.module.exports [作为符号] (D:\Mean_Projects\meanauthapp\node_modules\jsonwebtoken\sign.js:108:7) 在 User.comparePassword (D:\Mean_Projects\meanauthapp\routes\users.js:86:27) 在 bcrypt.compare (D:\Mean_Projects\meanauthapp\models\user.js:53:9) 在 D:\Mean_Projects\meanauthapp\node_modules\bcryptjs\dist\bcrypt.js:297:21 在 D:\Mean_Projects\meanauthapp\node_modules\bcryptjs\dist\bcrypt.js:1353:21 在 Immediate.next [as _onImmediate] (D:\Mean_Projects\meanauthapp\node_modules\bcryptjs\dist\bcrypt.js:1233:21) 在 runCallback (timers.js:785:20) 在 tryOnImmediate (timers.js:747:5) 在 processImmediate [as _immediateCallback] (timers.js:718:5)

这是我的护照代码

    const JwtStrategy= require('passport-jwt').Strategy;
    const ExtractJwt=require('passport-jwt').ExtractJwt;
    const User= require('../models/user');
    const config=require('../config/database');        
    module.exports=function(passport){
    let opts={};
    opts.jwtFromRequest=ExtractJwt.fromAuthHeader();
    opts.secretOrKey=config.secret;
    opts.issuer = 'accounts.examplesoft.com';
    opts.audience = 'yoursite.net';
    passport.use(new JwtStrategy(opts,(jwt_payload,done)=>{
        console.log(jwt_payload);
        User.getUserById(jwt_payload._doc._id,(err,user)=>{
            if(err){
                return done(err,false);
            }
            if(user){
                return done(null,user);
            }
            else{
                return done(null,false);
            }
        });
    }));
}

我的身份验证和获取配置文件代码

// Authenticate
router.post('/authenticate', (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;

  User.getUserByUsername(username, (err, user) => {
    if(err) throw err;
    if(!user){
      return res.json({success: false, msg: 'User not found'});
    }

    User.comparePassword(password, user.password, (err, isMatch) => {
      if(err) throw err;
      if(isMatch){
        const token = jwt.sign(user, config.secret, {
          expiresIn: 604800 // 1 week
        });

        res.json({
          success: true,
          token: 'JWT '+token,
          user: {
            id: user._id,
            name: user.name,
            username: user.username,
            email: user.email
          }
        });
      } else {
        return res.json({success: false, msg: 'Wrong password'});
      }
    });
  });
});

// Profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
  res.json({user: req.user});
});

【问题讨论】:

    标签: javascript node.js angular jwt passport.js


    【解决方案1】:

    失败了

    const token = jwt.sign(user, config.secret, {
    

    出现错误“预期“有效负载”是一个普通对象”

    您的user 对象在此处初始化:

    User.getUserByUsername(username, (err, user)
    

    我假设是mongoosejs 对象,它包含许多方法并且不是“可序列化的”。您可以通过传递一个普通对象来处理这个问题,或者使用来自mongoose.lean() 或普通的toJSON 方法:

    const token = jwt.sign(user.toJSON(), config.secret, {
      expiresIn: 604800 // 1 week
    });
    

    【讨论】:

    • @T.Meyer 请检查时间。显然我的答案(写于 2017 年)被 sushil50889 复制到 2018 年 github 上的 nodeauthapp 问题
    【解决方案2】:

    我也遇到了这个问题,从 mongoose 返回的用户,只需添加 toJSON()toObject() 即可解决问题,但如果您的用户并非总是来自 mongoose,会发生什么?

    你会得到一个

    user.toJson/user.ToObject 不是函数

    如果您尝试在普通对象上执行此操作。

    如果你的用户来自不同的来源并且你不知道它是否是一个普通的对象,你可以这样解决它:

    JSON.parse(JSON.stringify(user));
    

    【讨论】:

    • 这似乎是最好的答案
    • 你可以这样做:Object.assign({}, user)。浪费更少
    • 我的回答直接解决了 mongoose 的 OPs 问题。我认为对于其他情况有更好的解决方案,序列化/反序列化 JSON 并不是在所有情况下都是最佳的。
    【解决方案3】:

    migration doc of passport-jwt中明确提到了这一点

    他们已经从版本 2 和 3 中删除了 ExtractJwt.fromAuthHeader(),并且还使用新方法 ExtractJwt.fromAuthHeaderAsBearerToken() 或类似方法之一来代替旧方法。供参考visit

    从你的日志看有问题

    User.comparePassword (D:\Mean_Projects\meanauthapp\routes\users.js:86:27) at 
    

    所以这里有四件事需要在您的代码中更新@every Bit


    package.json 文件中的第一个
    使用 * 或 version no 将版本更改为最新版本 通过转到项目目录并运行命令

      npm install passport-jwt --save
        "dependencies": {
        ....     
            "passport-jwt": "^3.0.1"
          }
    

    或 写入文件并运行 commadn

    `npm install`
        "dependencies": {
            ....     
                "passport-jwt": "*"
              }
    

    第二次更改验证方法中的这行代码

    const token = jwt.sign(user.toJSON(), config.secret, {
      expiresIn: 604800 // 1 week
    });
    

    第三次在护照密码改旧方法

    ExtractJwt.fromAuthHeader();
    

    到新的,从文档参考你需要使用这个方法opts.jwtFromRequest=ExtractJwt.fromAuthHeaderWithScheme('jwt');

    第四个改变这个

    User.getUserById(jwt_payload._id,(err,user)=>{
    

    此解决方案适用于最新版本的


    • 如果您仍想使用这种旧方法,那么


    只需将 package.json 中的 passport-jwt 版本更改为 1.xx(x 是此处的数字),然后选择较低版本的 2
    移动到项目文件夹并运行命令npm install
    您唯一需要检查的是payload_jwt中的数据,它将在第二层,所以请检查jwt_payload。
    好的,你已经准备好了,你已经处理好了User.getUserById(jwt_payload._doc._id,(err,user)=>{

    【讨论】:

      【解决方案4】:

      这很简单,如果用户来自数据库(mongo)则只需执行user.toJSON(),如果用户来自任何其他来源则只需执行JSON.stringify(user)

      【讨论】:

        【解决方案5】:

        如果不是来自月光 然后使用扩展运算符

        const token = jwt.sign({ ...payload }, config.secret, {
          expiresIn: 100080
        });
        

        【讨论】:

          【解决方案6】:

          改变

          const token = jwt.sign(user, config.secret, { expiresIn: 10080 });
          

          收件人

          const token = jwt.sign(user.toJSON(), config.secret, { expiresIn: 10080 });
          

          【讨论】:

            【解决方案7】:
            const token = jwt.sign(user, config.secret, {
                  expiresIn: 604800 // 1 week
                });
            

            将其转换为

            const token = jwt.sign(user.toJSON(), config.secret, {
                  expiresIn: 604800 // 1 week
                });
            

            或者你需要 console.log(jwt_payload);查找您的 ID 在 _doc 下或直接使用 jwt_payload。因为这可能会随着版本而改变。

            【讨论】:

              猜你喜欢
              • 2020-09-23
              • 1970-01-01
              • 1970-01-01
              • 2019-07-30
              • 1970-01-01
              • 1970-01-01
              • 2015-10-30
              • 1970-01-01
              • 2017-11-26
              相关资源
              最近更新 更多