node.js 护照:未知的身份验证策略“本地”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41585947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:55:20  来源:igfitidea点击:

Passport: Unknown authentication strategy "local"

node.jsauthenticationpassport.js

提问by NVO

I'm new to NodeJS and I try to build a login/registration system. Registration works fine but I'm currently unable to login.

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

I find a example app using passport and nodejs, so based on this example I build the registration form and the login form. http://blog.robertonodi.me/node-authentication-series-email-and-password/

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

When I try to login I get an 'Unknown authentication strategy "local" error'. Can anybody explain what I'm doing wrong?

当我尝试登录时,我得到一个'Unknown authentication strategy "local" error'. 谁能解释我做错了什么?

My code

我的代码

(edit: added some changes from answers/comments and filenames)

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

Express config (config/express.config.js)

快速配置 (config/express.config.js)

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();
})

Passport config (config/auth.config.js)

护照配置 (config/auth.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
}

Local strategy (/config/strategies/local-strategy.js)

本地策略 (/config/strategies/local-strategy.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);
        })
    }))
}

Auth Controller (login only) (/controllers/auth.controller.js)

身份验证控制器(仅限登录)(/controllers/auth.controller.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);
}

回答by Ravi Shankar Bharti

You forgot to import passport config file in your app.js.

您忘记在您的app.js.

importpassport configafter initializing passport.

importpassport 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);

Hope this helps.

希望这可以帮助。

回答by Eassa Nassar

i have done like this and it worked

我已经这样做了并且有效

$npm install passport-local

$npm 安装通行证本地

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);
    });
  }
));