我是node.js身份验证新手。我想使用护照,本地护照,做一些基本的身份验证。但是当我尝试它时,它总是会失败。
我正在学习本教程 http://www.sitepoint.com/local-authentication-using-passport-node-js/
这是我到目前为止所做的:
var express = require('express');
var app = express();
var qs = require('querystring');
var pg = require('pg');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
//var expressSession = require('express-session');
//app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
// in here I know I am supposed to connect to database, and check if the username,password is there, but for now, i'll just force it to return a user, like they exist.
passport.use(new LocalStrategy(function(username, password, done) {
console.log(1); // does not even print this
//return done(null, false);
var r = done(null, {
'username': username,
'password': password
});
console.log(r);
return r;
}));
/*
* Visit the home page.
*/
app.get('/', function (req, res) {
var dest = 'index.html';
res.sendFile(dest, { root: __dirname });
});
/*
* Login.
*/
app.post('/login',
passport.authenticate('local', {
successRedirect: '/loginSuccess.html',
failureRedirect: '/loginFailure.html'
})
);
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('My App started at http://%s:%s', host, port);
});
有谁知道这有什么问题?
也可以解释一下这种基本身份验证的工作方式,以及序列化/反序列化功能的用途吗?
由于
答案 0 :(得分:2)
您的应用缺少body-parser
中间件,这是解析传入的POST
数据所必需的。
...
app.use(bodyParser.urlencoded({ extended : true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
...