护照本地猫鼬错误消息不起作用

时间:2021-04-16 12:46:56

标签: node.js mongodb express jwt passport-local

我正在使用 passport-local-mongoosemongoDB 中使用 JWT 对用户进行身份验证,一切正常,问题是当用户发送错误的用户名或密码响应总是“未经授权”,即使我在选项中指定 errorMessages 这里是我的代码:

用户模型:

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const passportLocalMongoose = require('passport-local-mongoose')

var userSchema = new Schema({
   admin:{
       type:Boolean,
       default:false
   },
   firstName:{
       type:String,
       default:''
   },
   lastName:{
       type:String,
       default:''
   },
   email:{
       type:String,
       default:''
   }
 })

 const options = {
  usernameQueryFields:['email'],
  errorMessages: {
    MissingPasswordError: 'No password was given',
    AttemptTooSoonError: 'Account is currently locked. Try again later',
    TooManyAttemptsError: 'Account locked due to too many failed login attempts',
    NoSaltValueStoredError: 'Authentication not possible. No salt value stored',
    IncorrectPasswordError: 'Password or username are incorrect',
    IncorrectUsernameError: 'Password or username are incorrect',
    MissingUsernameError: 'No username was given',
    UserExistsError: 'A user with the given username is already registered'
  },

}

userSchema.plugin(passportLocalMongoose,options)

var Users = mongoose.model('User',userSchema)

module.exports = Users

这是我验证用户的方式:

exports.local = passport.use(new LocalStrategy((User.authenticate())))
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())


exports.getToken = function(user){
return jwt.sign(user,config.secretKey,{expiresIn:100000})
}

const opt = {};
opt.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
opt.secretOrKey = config.secretKey

exports.jwtStrategy = passport.use(new JwtStrategy(opt,(jwt_payload,done) =>{
User.findOne({_id:jwt_payload._id})
.then((user) =>{
    done(null,user)
},(err) => done(err,false))
.catch((err) =>{
    done(err,false)
})
}))

exports.verifyUser = passport.authenticate('jwt',{session:false})

在用户路由器中:

router.post("/login",cors.corsWithOptions, passport.authenticate('local'), (req, res) => {

var token = authenticate.getToken({_id:req.user._id})

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token:token , status: 'You are successfully logged in!'});

});

这是我在用户传递错误凭据时得到的信息: this is what i got when user pass wrong credentials:

0 个答案:

没有答案