passportjs 本地策略没有被调用

passportjs local strategy not getting called

我正在使用 express 和 passport 构建一个休息 api 后端,我的 localStrategy 似乎没有按要求被调用。

我的应用程序的入口点如下所示:

app.js

var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/config');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');

var app = express();

app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({extended:true})); 

app.use(passport.initialize());

//connect to mongodb
mongoose.connect(config.db, options);

//load models (shorten forEach)
...
require(__dirname + '/models/' + file)(mongoose);

//load passport config
require('./config/passport')(mongoose, passport);

//load routes
require('./config/routes')(app, passport);

//start server
var server = app.listen(3000, ....

routes.js

...
app.post('/auth', function(req, res){
    console.log("reached auth endpoint");
    console.log(req.body);
    passport.authenticate('local', { session: false}, function(err, user, info){
      console.log("Test:"+user);
      if(err) {
        console.log("Error1");
        return next(err)}
      if(!user){
        console.log("Error2");
        return res.json(401, {error: 'Auth Error!'});
      }
      console.log("Error3");
      var token = jwt.encode({ username: user.email }, "hanswurst");
      res.json({token: token});
    }),
    function(req, res){
      console.log("passport user", req.user);
    };
  });

passport.js

...
passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  },
  function(email, password, done){
    console.log("TEST");
    User.findOne({'email': email}, function(err, user){
      if(err){
        console.log("Unknown error");
        return done(err);
      }
      if(!user){
        console.log("No User found");
        return done(null, false);
      }
      if(!user.validPassword(password)){
        console.log("Password was incorrect");
        return done(null, false);
      }
      console.log("User was found");
      return done(null, user);
    });
  }
));

我在表单请求中得到的唯一结果是

reached auth endpoint
{ email: 'test@mail.com', password: 'secret' }
POST /auth - - ms - -

对我来说,请求正文看起来不错,应该进入我的 LocalStrategy。我有点无助,因为我没有从这一点得到任何其他控制台输出。

首先,您在 routes.js 中有一些基本的 javascript 语法错误。此处的这部分(为清楚起见删除了大量代码)已损坏:

passport.authenticate(/*...*/), function(req, res) {/*..*/};

可能是您刚刚在错误的地方添加了一些 console.log 调用。为了消除混淆,passport.authenticate() 不会立即执行身份验证,它所做的是 return 为您提供的中间件。例如,您可以像这样使用它:

var middleware = passport.authenticate(...);
app.post('/auth', middleware);

因此,要解决您的问题,请尝试立即调用由 authenticate return 编辑的中间件,如下所示:

app.post('/auth', function(req, res, next) {
    console.log("reached auth endpoint");
    console.log(req.body);
    passport.authenticate('local', {
        session: false
    }, function(err, user, info) {
            console.log("Test:" + user);
            if (err) {
                console.log("Error1");
                return next(err);
            }
            if (!user) {
                console.log("Error2");
                return res.json(401, {
                    error: 'Auth Error!'
                });
            }
            console.log("Error3");
            var token = jwt.encode({
                username: user.email
            }, "hanswurst");
            res.json({
                token: token
            });
        })(req, res, next);
});

此外,我必须告诉你 require 缓存模块。为了让 config/passport.js 知道 mongoose 和 passport,你 不应该 像这样将它们作为参数提供:

require('./config/passport')(mongoose, passport);

只需在 config/passport.js 中再次要求它们,如下所示:

// (in config/passport.js)
// Both of these vars point to the same thing you require'd in app.js
var mongoose = require('mongoose');
var passport = require('passport');

[编辑] 我发现了问题。因为 Express 不再支持 body-parser 等子包,所以你需要单独设置它们。如果我一开始就这样做了,一切都会很好,但我只激活了:

app.use(bodyParser.urlencoded({extended:true}));

您还需要设置

app.use(bodyParser.json());

让它正常工作。愚蠢的疏忽但仍然让我难住了 3 天。


我有同样的问题,但似乎对我没有任何作用。

我会按照执行顺序从上往下放代码

翡翠模板

.navbar-right(ng-controller="mvNavBarLoginCtrl")
  form.navbar-form
    .form-group
      input.form-control(placeholder='Email', ng-model='username')
    .form-group
      input.form-control(type='password', placeholder='password', ng-model='password')
    button.btn.btn-primary(ng-click="signIn(username,password)") Sign In

下一步登录控制器

angular.module('app').controller('mvNavBarLoginCtrl',function($scope, $http){
  $scope.signIn = function (username, password){

    console.log('un = ' + username);   // Prints fine in the console
    console.log('pw = ' + password);   // Prints fine in the console

    $http.post('/login', {username: username, password: password}).then(function(response){
      if(response.data.success){
        console.log('Logged in!!');
      }
      else{
        console.log('Failed to log in!!');
      }

    });
  }
});

下一步路由处理程序

app.post('/login', function(req, res, next){
      console.log(req.username);   // Already empty
      console.log(req.password);   // Already empty
      console.log(req.body);       // Already empty

      // Because of the use of AngularJS we can not call passport directly, 
      // missing req and res will break the code 

      var auth = passport.authenticate('local', function(err, user){

          console.log(user);     // prints undefined

          if(err){return next(err);}

          if(!user){res.send({success:false});}

          req.logIn(user, function(err){

              if(err){return next(err);}

              res.send({success: true, user: user});
          });

      });
      // call the auth function to start authenticate
      auth(req, res, next);
  });

下一步护照身份验证处理程序

var User = mongoose.model('User');

passport.use(new LocalStrategy({
      username: 'username',
      password: 'password'
    },
    function(username, password, done){

      console.log("called");  // never printed

      // find user based in mongoose schema see 'var User' 
      User.findOne({userName:username}).exec(function (err,user){

        console.log(user)     // never printed
        if(err){return done(err);}

        if(user){
          return done(null, user);
        }
        else{
          return done(null, false);
        }
      });
    }
));


passport.serializeUser(function(user, done){
  if(user) {
    done(null, user._id);
  }
});

passport.deserializeUser(function(id, done){
  user.findOne({_id:id}).exec(function(err, user){
    if(user) {
      done(null, user);
    }
    else{
      done(null, false);
    }
  });
});

没有错误不在控制台中,也不作为节点输出。我很困惑并阅读了大约 5 个具有类似问题的其他线程,但没有任何效果。

如果有人能给我金点子,我将感激不尽。