使用令牌,护照jwt,Express进行身份验证

时间:2018-03-24 21:31:25

标签: javascript express passport.js

我正在处理这个小项目而我遇到了困难,除了当我想使用令牌对用户进行身份验证时,一切都在我的api中工作正常,它表示"未授权&#34 ;。任何帮助将非常感激。 这是我的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.fromAuthHeaderWithScheme('jwt');
       opts.secretOrKey = config.secret;
       passport.use(new jwtStrategy(opts, function(jwt_payload, done) 
       {
       User.getUserById(jwt_payload.data._id, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);
        }
    });
}));

}

这是我的user.js文件(我认为错误在getUserById函数中:

       const mongoose = require('mongoose');
       const bcrypt = require('bcryptjs');
       const config = require('../config/database');
      //User schema
      const userSchema = mongoose.Schema({
      name: {
     type: String
     },
      email: {
         type: String,
         required: true
       },
      username: {
        type: String,
        required: true
         },
         password: {
           type: String,
           required: true,
       }

     });

    const User = module.exports = mongoose.model('User', userSchema);

   module.exports.getUserById = function(id, callback){
     User.findById(id, callback);
    }
   module.exports.getUserByUsername = function(username, callback){
   const query = {username: username}
   User.findOne(query, callback);
   }
    module.exports.addUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt){
    bcrypt.hash(newUser.password,salt,function(err, hash){
        if(err) throw err;
        newUser.password= hash;
        newUser.save(callback);
       });
     });
  }
    module.exports.comparePassword = function (candidatePassword, 
    hash, callback){
     bcrypt.compare(candidatePassword, hash, function(err, isMatch){
    if(err) throw err;
    callback(null, isMatch);
    });
    }

0 个答案:

没有答案