参考文档:passport 官网
一、安装
npm install express --save
npm install body-parser cookie-parser cookie-session --save
npm install passport passport-local --save
npm install express --save
npm install ejs --save
二、passport 策略
// passport 策略
passport.use(new LocalStrategy((username, password, done) => {
// 获取 user
const user = {
id: 1,
username: 'admin',
password: '1'
}
if (username !== user.username) {
return done(null, false, {message: 'incorrect username'});
}
if (password !== user.password) {
return done(null, false, {message: 'incorrect username'});
}
return done(null, user);
}));
// 序列化
passport.serializeUser((user, done) => {
done(null, user)
});
// 反序列化
passport.deserializeUser((user, done) => {
done(null, user);
});
三、路由
// 路由
app.get('/', (req, res) => {
res.render('index', {title: '登录面'})
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/user',
failureRedirect: '/'
}),
(req, res) => {
console.log('嘿嘿')
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.all('/user', (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/')
});
app.get('/user', (req, res) => {
var html = "<h2>你好, " + req.user.username + "</h2><a href='/logout'>退出</a>";
res.send(html);
});
四、完整代码 app.js
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
// pasport 策略
...
// 中间件
app.use(express.static('public'));
app.use(bodyParser({
extended: false
}))
app.use(cookieParser());
app.use(cookieSession({
secret: 'secret',
maxAge: 1000*60*60
}));
app.use(passport.initialize());
app.use(passport.session());
// 模板
app.set('view engine', 'ejs');
app.engine('ejs', ejs.renderFile);
// 路由
...
const server = app.listen(4000, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`app listening on:${host}:${port}`);
});
五、模板 views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= title %></title>
</head>
<h1>Login</h1>
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" />
</div>
<div>
<input type="submit" value="Log In" />
</div>
</form>
</body>
</html>