web-dev-qa-db-ja.com

NodeJS TypeError( 'JwtStrategy require a secret or key');

私はJwtStrategy実装を試しましたが、

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

  2. User.getUserById(jwt_payload._doc._id、(err、user)

これは、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...

内部ser.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'});
   } 
});
});
});
9
Asutosh

同じ問題に会った。これは、optionsに渡される最初のJwtStrategy引数に有効なsecretOrKeyが必要なためです。 secretOrKeyundefinedを終了すると、エラーが発生します。

私の場合、dotenvを使用して_process.env_変数を読み取り、_process.env.SECRET_にアクセスする前にrequire('dotenv').config();が呼び出されていることを確認する必要があります。

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

keys.jsファイルを次のように作成します

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

(注:secretOrKey:秘密またはPEMエンコードされた公開鍵を含む文字列またはバッファ。secretOrKeyProviderが提供されていない場合は必須。* secretOrKeyProvider:secretOrKeyProvider(request、rawJwtToken、done)形式のコールバック)、*
これは、doneまたはPEMエンコードされた公開鍵でdoneを呼び出す必要があります*
(非対称)指定されたデコードされていないjwtトークン文字列とリクエスト*の組み合わせ。 doneには、署名関数done(err、secret)があります。 *
secretOrKeyが提供されていない場合は必須。 )

passport.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
    })
  );
};``

あなたがする必要があるすべて

1
manoj T.