express 基于 passport,passport-local 本地身份验证

参考文档: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 = "

你好, " + req.user.username + "

退出"; 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




  
  
  
  <%= title %>

Login

你可能感兴趣的:(express 基于 passport,passport-local 本地身份验证)