错误:未知的身份验证策略" local" (快递和护照)

时间:2016-09-27 14:27:40

标签: javascript mongodb express passport.js passport-local

我试图在快递应用程序中使用护照身份验证。

router.get('/signup', (req ,res) => {
  res.render('signup');
});

router.post('/signup', function(req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  User.findOne({ username: username }, function(err, user) {

    if(err) { return next(err); }
    if(user) {
      req.flash('error', 'User already exists');
      return res.redirect('/signup');
    }

    var newUser = new User({
      username: username,
      password: password
    });
    newUser.save(next);
  });
}, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/signup',
  failureFlash: true
}));

每当我尝试注册测试用户时,它都有效,但它会显示如下错误:

Error: Unknown authentication strategy "local"

你能告诉我一件事。

2 个答案:

答案 0 :(得分:3)

看起来您尚未设置Passport以使用您的护照本地策略。 您需要导入它,实例化它,然后指示Passport使用它。这是一个例子:

var LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

router.post('/signup', function(req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  User.findOne({ username: username }, function(err, user) {

    if(err) { return next(err); }
    if(user) {
      req.flash('error', 'User already exists');
      return res.redirect('/signup');
    }

    var newUser = new User({
      username: username,
      password: password
    });
    newUser.save(next);

    passport.authenticate('local', { failureRedirect: '/signup' }),
     function(req, res) {
      res.redirect('/');
    });
  });
});

请阅读该插件的文档here。 此外,here's an example app使用该身份验证策略。

答案 1 :(得分:0)

尝试在本地之后使用回调函数而不是传递对象。像这样:

    router.post("/register", function(req, res){
      var newUser = new User({username: req.body.username});
      User.register(newUser, req.body.password, function(err, user){
          if(err){
              req.flash("error", err.message); //such as the username is taken or no username entered etc.
              res.redirect("/register");
          } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
              });
            }
        });
    });