【问题标题】:getting an error "throw new TypeError('JwtStrategy requires a secret or key');"收到错误“throw new TypeError('JwtStrategy requires a secret or key');”
【发布时间】:2019-01-14 13:11:00
【问题描述】:

我正在尝试制作一个 Web 应用程序,但在尝试运行几个文件时出现此错误:

throw new TypeError('JwtStrategy requires a secret or key');
        ^

TypeError: JwtStrategy requires a secret or key
    at new JwtStrategy (/Users/smitsanghvi/Desktop/project/node_modules/passport-jwt/lib/strategy.js:45:15)
    at module.exports.passport (/Users/smitsanghvi/Desktop/project/config/passport.js:12:18)
    at Object.<anonymous> (/Users/smitsanghvi/Desktop/project/index.js:27:29)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
[nodemon] app crashed - waiting for file changes before starting...

我确实将密钥传递给 JWS 策略,但仍然出现错误。

passport.js

const jwtStrategy=require('passport-jwt').Strategy;
const ExtractJwt=require('passport-jwt').ExtractJwt;
const mongoose=require('mongoose');
const User=mongoose.model('User');
const key=require('../config/key');

const options={};
options.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey=key.secretOrKey;

module.exports=passport=>{
    passport.use(new jwtStrategy(options,(jwt_checking, done)=>{
        console.log(jwt_checking);
        User.findById(jwt_checking.id).then(user=>{
            if(user){
                return done(null, user);
            }
            return done(null,false);
        })
        .catch(err=>console.log(err))
    }))
}

这是应用程序的主文件。 index.js

const express= require('express');
const mongoose=require('mongoose');
const bodyParser=require('body-parser');
const user=require('./route/api/user');
const userprofile=require('./route/api/userprofile');
const passport=require('passport');
const key=require('./config/key');


const app=express();
//body parser middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//database confid into variable using variable name that I used in key.js of config folder
const database=require('./config/key').mongoURI;

//connecting to mongodb
//.then will print connected if successful
//catch will print error if not
mongoose.connect(database).then(()=>console.log("connected")).catch(err=>console.log(err));

//passport middleware
app.use(passport.initialize());

//passport config
require('./config/passport')(passport);

//gave port number 3000 input to run
//using route to check the output of user.js and userprofile.sj
app.use('/api/user',user);
app.use('/api/userprofile',userprofile);
//will run at 3000 port on localhost
const port=process.env.PORT || 3000;

//it will print this in the terminal after npm start or npm run server 
//this will print the consr port in conlsole
app.listen(port,()=> console.log('port is:: ${port}'));

user.js

const express=require('express');
const router=express.Router();
const bcrypt=require('bcryptjs');
const user=require('../../model/User');
const jwt=require('jsonwebtoken');
const key=require('../../config/key');
const passport=require('passport');


router.get('/demo',(req,res)=>res.json({output:"user"}));

//creating route for regsiteration
//using postman it will get this 
router.post('/register',(req,res)=>{
    //find if email exists or not.
    user.findOne({email: req.body.email}).then(user=>{
        if(user){
            return res.status(400).json({email:"email is already registered"});
        }
        else{
            //else will creaete new user
            const newUser=new User({
                name: req.body.name,
                email:req.body.email,
                password:req.body.password
            })

            //generate salt and hash pass with salt
            bcrypt.genSalt(10,(err,salt)=>{
                //hashing password
                bcrypt.hash(newUser.password, salt, (err,hash)=>{
                    if(err) throw err;
                    //after setting hash password will save it
                    newUser.password=hash;
                    newUser.save()
                    //then will return through json
                    .then(user=>res.json(user))

                })
            })
        }
    })
});

//returning jason web token
router.post('/login',(req,res)=>{
    const email=req.body.email;
    const password=req.body.password;
    //will find user by email
    //will check if email and pass is present in mlab db
    User.findOne({email}).then(user=>{
        if(!user){
            return res.status(404).json({email:"user doesnt exist"});
    }
    //
            bcrypt.compare(password,user.password).then(isMatch=>{
                if(isMatch){
                    //user matched
                    //checking will check the details of user
                    const checking={id: user.id,name:user.name}
                    //
                    jwt.sign(checking,key.key1,(err,token)=>{
                        res.json({
                            access:true,
                            token:token
                        })
                    });

            }
                    else{
                    return res.status(400).json({password:"password incorrect"});
        }

            })

    })
})

router.get(
    '/current',
    passport.authenticate('jwt',{session:false}), 
    (req,res)=>{
    res.json({
        id:req.user.id,
        name:req.user.name,
        email:req.user.email


})
    }
)


module.exports=router;

所有软件包都已正确安装。我无法解决这个问题,最终应用程序崩溃了。

【问题讨论】:

  • 变量中真的有键吗?在passport.js中尝试console.log(key.secretOrKey);

标签: node.js express npm jwt passport.js


【解决方案1】:

const options={}; options.jwtFromRequest=ExtractJwt.fromAuthHeaderAsBearerToken(); options.secretOrKey=key.secretOrKey;

您可以将“options”变量名称更改为新的变量名称,因为“options”是由您的编辑器定义的“多个定义”。改个名字就行了我和你遇到了同样的问题。我希望这种方式可以帮助您解决问题。

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2022-12-26
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    相关资源
    最近更新 更多