使用护照中间件的身份验证失败永远不会被调用

时间:2017-03-10 15:01:23

标签: node.js passport.js middleware passport-local

以下程序使用passportjs进行用户名/密码身份验证。我不是犯了什么错误,但我总是被重定向到失败页面,即再次回到登录页面。

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


var app = express();

app.listen(3000);

app.use(express.static(__dirname+'/public'));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
  function(username, password, done) {
     console.log(username + ':username');
     console.log(password + ':password');
     return done(null, [{username:'foo'}]);
  }
));

app.get('/login',(req,resp) => {
    var options = {
        root: __dirname + '/public/'
    };

    resp.sendFile('login.html',options);
});

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'})
);

我正在尝试理解passportjs的工作,我发现中间件passport.use(new LocalStrategy(永远不会被调用。我不知道原因,但可能是失败的根本原因。

2 个答案:

答案 0 :(得分:0)

也许护照需要会话尝试在护照配置之前添加app.use(express.session({ secret: 'keyboard cat' }));

您必须为策略命名并序列化用户

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

passport.use('local', new LocalStrategy(
  function(username, password, done) {
     console.log(username + ':username');
     console.log(password + ':password');
     return done(null, [{username:'foo'}]);
  }
));

您可以通过此名称local

按名称调用此策略
app.post('/login',
  passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'})
);

答案 1 :(得分:0)

所以我错过了passportjs要求解析帖子请求的body parser模块。这是完整的代码:

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy
  , express = require('express')
  , bodyParser = require('body-parser');


var app = express();

app.listen(3000);

app.use(express.static(__dirname+'/public'));
app.use(bodyParser.urlencoded({ extended: false }));// parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(passport.initialize());
app.use(passport.session());

passport.use('local',new LocalStrategy(
  function(username, password, done) {
     console.log(username + ':username');
     console.log(password + ':password');
     return done(null, {username:username});
  }
));

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

passport.deserializeUser(function(id, done) {
   done(null, user);
});


app.get('/login',(req,resp) => {
    var options = {
        root: __dirname + '/public/'
    };

    resp.sendFile('login.html',options);
});

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'})
);