Node.js 模块之【passport】第三方【Github】鉴权(二)

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

Node.js 模块之【passport】第三方【Github】鉴权(二)

January 21, 2019 Uncategorized 0

1. 安装模块
npm i connect-mongo –save-dev
npm i passport –save-dev
npm i passport-github –save
1
2
3
2. 引入模块及其他依赖模块
var session = require(‘express-session’);
var MongoStore = require(‘connect-mongo’)(session);
var passport = require(‘passport’);
var GithubStrategy = require(‘passport-github’).Strategy;
1
2
3
4
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. 添加Github鉴权策略
passport.use(new GithubStrategy({
clientID:’【Your ClientID】’,
clientSecret:’【Your Secret】’,
callbackURL:’【Your CallBack】’
},function(accessToken,refreshToken,profile,done) {
UserModel.findOne({
githubId: profile.id
}, function(err, user) {
if (err) {
return done(err);
} else {
if (!user) {
user = new UserModel({
githubId:profile.id,
username:profile.username
});
user.save();
return done(null, user);
}else{
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
23
24
5. 使用connect-mongo保存
app.use(session({
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 36000000 /*单位:毫秒*/
},
secret: “robin shop”,
store: new MongoStore({
url:’mongodb://localhost/【Your MongoDB】’
})
}));
1
2
3
4
5
6
7
8
9
10
11
6. 封装权限检查中间件
var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated() || (req.user && req.user.provider)) {
return next();
}
res.redirect(‘/login’);
}
1
2
3
4
5
6
7. 设置Github登陆路由及其回调
app.get(‘/auth/github’, passport.authenticate(‘github’));

app.get(‘/auth/github/callback’, passport.authenticate(‘github’, {
failureRedirect: ‘/login’
}), function(req, res) {
res.redirect(‘/users’);
});
1
2
3
4
5
6
7
8. 登出销毁session
app.get(‘/logout’, function(req, res) {
req.logout();
res.redirect(‘/login’);
});
1
2
3
4
9. 权限限定
app.use(‘/users’, isAuthenticated, users);
app.use(‘/products’, isAuthenticated, products);
app.use(‘/upload’, isAuthenticated, upload);
———————
作者:zhagener
来源:CSDN
原文:https://blog.csdn.net/zhagener/article/details/62235631
版权声明:本文为博主原创文章,转载请附上博文链接!

Leave a Reply

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