Node.js 模块之【passport】进行本地【用户名+密码】鉴权(一)

小醋说:我是吃不饱的^_^

Node.js 模块之【passport】进行本地【用户名+密码】鉴权(一)

January 21, 2019 Uncategorized 0

1. 安装 passport
npm i passport
npm i passport-local
1
2
2. 添加模块(上面几个为依赖模块)
var cookieParser = require(‘cookie-parser’);
var bodyParser = require(‘body-parser’);
var session = require(‘express-session’);
var MongoStore = require(‘connect-mongo’)(session);
var passport = require(‘passport’);
var LocalStrategy = require(‘passport-local’).Strategy;
1
2
3
4
5
6
3. 实现一些基本回调
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
UserModel.findById(id, function(err, user) {
done(err, user);
})
});
1
2
3
4
5
6
7
8
9
4. 使用本地策略

passport.use(new LocalStrategy(function(username, password, done) {
UserModel.findOne({
username: username
}, function(err, user) {
if (err) {
return done(err);
} else {
if (!user) {
return done(null, false, {
message: ‘用户名不存在’
});
}
if (!user.password == password) {
return done(null, false, {
message: ‘密码不匹配’
});
}
return done(null, user);
}
});
}));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
5. login时,通过logIn方法设置状态
app.post(‘/login’, function(req, res, next) {
passport.authenticate(‘local’, function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.redirect(‘/login’);
}
// res.redirect(‘/users’);
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect(‘/users’);
});
})(req, res, next);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
6. 将passport中自定义的req.isAuthenticated 封装为插件

var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect(‘/login’);
}
1
2
3
4
5
6
7
7. 设置session保存至数据库
app.use(session({
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3600000 //单位:毫秒
},
secret: “robin shop”,
store: new MongoStore({
url:’mongodb://localhost/emberExpressMongoDB’
})
}));
1
2
3
4
5
6
7
8
9
10
11
8. 初始化passport
app.use(passport.initialize());
app.use(passport.session());
1
2
9. 路由中的使用
app.use(‘/users’, isAuthenticated, users);
———————
作者:zhagener
来源:CSDN
原文:https://blog.csdn.net/zhagener/article/details/62042931
版权声明:本文为博主原创文章,转载请附上博文链接!

Leave a Reply

Your email address will not be published. Required fields are marked *