NodeJS TypeError(' JwtStrategy需要密钥或密钥');

时间:2017-08-05 18:16:43

标签: node.js passport.js

我已经尝试过JwtStrategy实现我已经取代了

  1. User.findOne({id:jwt_payload.id} with

  2. User.getUserById(jwt_payload._doc._id,(错误,用户)

  3. 位于user.js文件中 运行index.js时得到的错误是: -

    H:\rprfinal\node_modules\passport-jwt\lib\strategy.js:29
            throw new TypeError('JwtStrategy requires a secret or key');
            ^
    TypeError: JwtStrategy requires a secret or key
        at new JwtStrategy (H:\rprfinal\node_modules\passport-jwt\lib\strategy.js:29:15)
        at module.exports (H:\rprfinal\config\passport.js:10:18)
        at Object.<anonymous> (H:\rprfinal\index.js:42:29)
        at Module._compile (module.js:569:30)
        at Object.Module._extensions..js (module.js:580:10)
        at Module.load (module.js:503:32)
        at tryModuleLoad (module.js:466:12)
        at Function.Module._load (module.js:458:3)
        at Function.Module.runMain (module.js:605:10)
        at startup (bootstrap_node.js:158:16)
        at bootstrap_node.js:575:3
    [nodemon] app crashed - waiting for file changes before starting...
    

    user.js 文件中: -

    module.exports.getUserById = function(id, callback){
        User.findById(id, callback);
    }
    

    index.js 档案: -

         //Body parser Middleware
    app.use(bodyParser.json());
    
        //Passport Middleware 
    app.use(passport.initialize());
    app.use(passport.session());
    
    require('./config/passport')(passport);
    
    app.use('/users',users);
    

    passport.js 档案: -

    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;
        passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
            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);
                }
            });
        }));
    }
    

    和users.js包含注册和身份验证

     // 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'});
       } 
    });
    });
    });
    

3 个答案:

答案 0 :(得分:3)

遇到同样的问题。这只是因为传递给options的第一个JwtStrategy参数必须具有有效的secretOrKey。离开secretOrKey undefined会出错。

在我的情况下,我使用dotenv来阅读process.env变量,并且必须确保在访问require('dotenv').config();之前调用process.env.SECRET

require('dotenv').config();
const jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.SECRET
};
const strategy = new JwtStrategy(jwtOptions, function (payload, done) {
    // ...
});

答案 1 :(得分:0)

创建一个keys.js 文件如下

module.exports = {    
    secretOrKey: 'yoursecretkeyishere'
};
  

(注意:secretOrKey:包含机密或   PEM编码的公钥。除非secretOrKeyProvider是   提供。 * secretOrKeyProvider:回调格式   secretOrKeyProvider(request,rawJwtToken,done),*
  应该使用秘密或PEM编码的公钥完成调用*
  (非对称)给定的未解码jwt令牌字符串和请求*   组合。 done具有签名功能done(err,secret)。 *
  除非提供secretOrKey,否则为必需。 )

在password.js文件中

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('users');
const keys = require('../config/keys');

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => {
  passport.use(
    new JwtStrategy(opts, (jwt_payload, done) => {
      //Your logic here
    })
  );
};``

这就是您要做的一切

答案 2 :(得分:-3)

尝试:

const config = require('./config/database');