护照:未知的身份验证策略“本地" [英] Passport: Unknown authentication strategy "local"

查看:181
本文介绍了护照:未知的身份验证策略“本地"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是NodeJS的新手,我尝试构建一个登录/注册系统.注册可以正常进行,但我目前无法登录.

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

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

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/

当我尝试登录时,我得到一个'Unknown authentication strategy "local" error'.有人可以解释我在做什么错吗?

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

(添加了对答案/评论和文件名的一些更改)

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

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

护照配置(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
}

本地策略(/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);
        })
    }))
}

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

推荐答案

您忘记了在app.js中导入护照配置文件.

You forgot to import passport config file in your 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);

希望这会有所帮助.

这篇关于护照:未知的身份验证策略“本地"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆