- Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
这里是最详尽的文档: http://passportjs.org/docs/authenticate
上面的文档对flash message的叙述有误
见Node.js Authentification with Passport: How to flash a message if a field is missing?
其中有提到这篇博客: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
写得非常详细.
Quick start
要快速开始可以看github page首页上的express 4 demo, 按我的理解快速记下几个要点:
passport只用在login的那一刻, 也就是说, 有且只用在一个地方.
router.post('/login',passport.authenticate('strategyName',{params}),(req,res)=>{//这里就可以使用req.user得到用户, 会包含在 deserializeUser 函数中传入的 user 数据}在其它地方可以使用req.isAuthenticated()来判断用户是否登录了, 但我们一般都会把user放在session里, 然后判断req.session.user是否存在, 所以这个isAuthenticated方法不是很有必要.
要使用上面的代码能正常运行, 需要向passport注册一些Strategy(目前有300多种strategy可用), 官网首页上有个列表, qq, weibo, weixin, twitter, facebook你能想到的都在里边.
这个strategy name默认叫'local', 就是常用的用form表单提交用户密码的情况.
以下是配置部分, 用代码说话:
Strategies 注册Strategy
passport.use(/* 'your random strategy name here' */,newLocalStrategy(function(username,password,done){User.findOne({username: username},function(err,user){if(err){returndone(err);}if(!user){returndone(null,false);}if(!user.verifyPassword(password)){returndone(null,false);}returndone(null,user);});}Sessions 序列化与反序列化
passport.serializeUser(function(user, done){done(null, user.id)}); passport.deserializeUser(function(id, done){User.findById(id, function (err, user){done(err, user)})}); Middleware 依赖的组件
varapp=express();app.use(require('serve-static')(__dirname+'/../../public'));app.use(require('cookie-parser')());app.use(require('body-parser').urlencoded({extended: true}));app.use(require('express-session')({secret: 'keyboard cat',resave: true,saveUninitialized: true}));app.use(passport.initialize());app.use(passport.session());Authenticate Requests 仅用在登录处
app.post('/login',passport.authenticate('local',{failureRedirect: '/login'}),function(req,res){res.redirect('/');});也可以这样
router.post('/',passport.authenticate('local',{successRedirect: 'http://localhost:3000',failureRedirect: '/login'}));References
Metadata
Metadata
Assignees
Labels
No labels