Passport:未知的身份验证策略“本地”

时间:2017-01-11 08:27:43

标签: node.js authentication passport.js

我是NodeJS的新手,我尝试构建一个登录/注册系统。注册工作正常,但我目前无法登录。

我找到了一个使用passport和nodejs的示例应用程序,因此基于此示例,我构建了注册表单和登录表单。 http://blog.robertonodi.me/node-authentication-series-email-and-password/

当我尝试登录时,我得到app.use(session({ store: new MongoStore({ url: 'mongodb://' + config.url + ':' + config.port + '/' + config.name }), secret: 'secretkey', key: 'skey.sid', resave: false, saveUninitialized: false, cookie : { maxAge: 604800000 //7 days in miliseconds } })); app.use(passport.initialize()); app.use(passport.session()); require(path.join(__dirname, 'auth.config'))(passport); //Load passport config app.use(function(req, res, next) { req.resources = req.resources || {}; // res.locals.app = config.app; res.locals.currentUser = req.user; res.locals._t = function (value) { return value; }; res.locals._s = function (obj) { return JSON.stringify(obj); }; next(); }) 。谁能解释我做错了什么?

我的代码

(编辑:从答案/评论和文件名中添加了一些更改)

Express config(config / express.config.js)

var path = require('path');

var passport=require('passport');
var User = require(path.join(__dirname, '..', 'models', 'user.model'));

module.exports = function(passport) {

    passport.serializeUser(function(user, done){
        done(null, false);
    });
    passport.deserializeUser(function(id, done){
        console.log("deserializeUser called", id);
        User.findById(id, function (err, user) {
            done(err, user);
        });
    });

    //load strategy files
    require(path.join(__dirname, 'strategies', 'local-strategy'));
    //TODO: Facebook
    //TODO: Twitter
    //TODO: Google
}

Passport config(config / auth.config.js)

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

module.exports = function () {
    console.log("LocalStrategy called");
    passport.use(new LocalStrategy({
        usernameField : 'username',
        passwordField : 'password'
    },
    function(username, password, done) {
        User.authenticate(username, password, function(err, user) {
            if (err) {
                return done(err);
            }

            if(!user) {
                return done(null, false, {message: 'Invalid username or password'});
            }

            return done(null, user);
        })
    }))
}

本地策略(/config/strategies/local-strategy.js)

module.exports.loginUser = function(req,res, next) {
    console.log("Auth.config", path.join(__dirname, 'strategies', 'local-strategy'))
   passport.authenticate('local', function (err, user, info) {
       if (err || !user) {
           console.log("Error", info);
           return res.status(400).send(info);
       }

       req.logIn(user, function(err) {
           if (err) {
              return next(err);
              // return res.status(404).send("Username or password incorrect");
           }
       })

       res.status(200).json(user);
   })(req, res, next);
}

Auth Controller(仅限登录)(/ console.auth.controller.js)

{{1}}

3 个答案:

答案 0 :(得分:16)

您忘记在app.js

中导入护照配置文件 初始化import

passport config passport

app.use(passport.initialize());
app.use(passport.session());
// Add the line below, which you're missing:
require('./path/to/passport/config/file')(passport);

希望这有帮助。

答案 1 :(得分:1)

此修复错误。创建新的LocalStrategy时需要使用“本地”

passport.use('local', new LocalStrategy({
    usernameField:'useName',
    passwordField: 'password',
    passReqToCallback: true

答案 2 :(得分:0)

我已经这样做了并且有效

  

$ npm install passport-local

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy; /* this should be after passport*/



 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, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));