Passport
Node.js でセッション管理をしたくなったのですがやり方を忘れていたので備忘録にします。
Environments
% node -v v4.2.6
Prepare
% mkdir practice-passport && cd $_ % npm init --yes % git init && git add . && git commit -m 'first commit' % npm install --save express express-session passport passport-local body-parser
create app.js
add app.js
'use strict'; const express = require('express'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const user = { id: 1, username: 'okamuuu', password: 'password' }; // setup passport passport.use(new LocalStrategy((username, password, done) => { if (username === user.username && password === user.password) { return done(null, user); } done(null, false); })); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser(function(id, done) { // XXX: lookup user by id done(null, user); }); // setup express const app = express(); app.use(require('body-parser').urlencoded({ extended: true })); app.use(require('express-session')({ secret: 'fuga', resave: true, saveUninitialized: true, cookie: { maxAge: 30 * 60 * 10 } })); app.use(passport.initialize()); app.use(passport.session()); app.get('/', (req, res, next) => { if (!req.isAuthenticated()) { return res.status(401).send({ error: 'not found user' }); } res.send('Hello, world!'); }); app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), (req, res) => { res.redirect('/'); }); app.post('/logout', function(req, res){ req.logout(); res.send('Good bye!'); }); const PORT=5000 app.listen(PORT, () => { console.log(`Example app listening on port ${PORT}!`); });
Run app.js
% node app.js Example app listening on port 5000!
Operation check
ログインしていない
% curl -s "http://localhost:5000" -b test.cookie {"error":"not found user"}
ログインする
% curl -sL "http://localhost:5000/login" -d "username=okamuuu" -d "password=password" -c test.cookie Hello, world!
以後、cookie を送信すればログインできる
% curl -s "http://localhost:5000" -b test.cookie Hello, world!
ログアウトする
% curl -sL -X POST "http://localhost:5000/logout" -c test.cookie Good bye!
ログインできない
% curl -s -X POST "http://localhost:5000/logout"
Information
curl に -v
オプションをつけるとより情報を取得できます。
% curl -v "http://localhost:5000/" -b test.cookie
あと session store が Memory なのでプロセスを切るともう一度ログインし直す必要があります。
The session store instance, defaults to a new MemoryStore instance.