passport-local验证
2017-01-18
passport常用的local本地验证,默认使用用户名和密码来进行验证。
参考网上各种示例时,一定要注意express版本。express 4.x版本中已经将bodyParser中间件分离了,需要单独安装模块,就可以对post进行解析了。不然的话,验证时req.body会是undefined,始终通不过。
GitHub:
https://github.com/jaredhanson/passport-local
NPM:
https://www.npmjs.com/package/passport-local
依赖项:
"dependencies": {
"body-parser": "^1.15.2",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.3",
"express": "^4.14.0",
"express-session": "^1.14.2",
"passport": "^0.3.2",
"passport-local": "^1.0.0"
}
实例:
var express = require('express');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (username, done) {
done(null, username);
});
passport.use(new LocalStrategy(
function(username, password, done) {
//自定义验证方式, 一般会引入User模块操作数据库
return done(null, "user");
}
));
app.use(cookieParser());
app.use(session({
secret: 'woot',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.post('/login',
passport.authenticate('local', {
failureRedirect: '/error',
successRedirect: '/user'
}), function(req, res) { }
);
app.get("/error", function (req, res) {
res.send("login failed!");
});
app.get("/user", function (req, res) {
res.send("login success!");
});
By Pury.
