使用Node.js + Express + Passport-GitLab2来创建OAuth Application
首先
我们在本地搭建了自己的GitLab。
创建认证太麻烦了,用GitLab不就行了吗?
所以,让我们通过OpenID实现认证,同时使用OAuth进行授权吧!
这是一个关于前端初学者在实施中遇到困难并努力实现的记录。
护照-gitlab2
这是它的网址:https://www.npmjs.com/package/passport-gitlab2
前期准备
我会在GitLab上进行准备连接。
在【管理区域】→【应用程序】中进行设置。

结果
這就是這樣子了。
首先是添加依赖信息。
var passport = require('passport');
var session = require('express-session');
var GitLabStrategy = require('passport-gitlab2').Strategy;
接下来是关于启用会话的定义描述。
app.use(session({
secret: "secret-key",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: false,
secure: true,
maxage: 1000 * 60 * 30
}
}));
app.use(passport.initialize());
app.use(passport.session());
然后,描述认证URL和回调URL的定义。
app.get('/', passport.authenticate('gitlab'));
app.get('/auth/gitlab/callback',
passport.authenticate('gitlab', {
failureRedirect: '/error.html'
}),
function (req, res) {
// Successful authentication, redirect home.
res.redirect('/home');
});
然后,定义了从GitLab返回的认证处理以及反序列化/序列化处理。完成
//passport
passport.use(new GitLabStrategy({
clientID: process.env.GITLAB_APP_ID,
clientSecret: process.env.GITLAB_APP_SECRET,
callbackURL: process.env.GITLAB_CALLBACK,
baseURL: process.env.GITLAB_URL
},
function (accessToken, refreshToken, profile, done) {
if (profile) {
user = profile;
return done(null, { id: profile.id });
}
else {
return done(null, false);
}
}
));
passport.deserializeUser(function (id, done) {
console.log('Deserialize user called.');
return done(null, { "id": id });
});
passport.serializeUser(function (user, done) {
console.log('Serialize user called.');
return done(null, { id: user.id });
});
随后,对于各种路由规定必须进行身份认证。
function ensureAuthenticated(req, res, next) {
console.log("ensureAuthenticated");
if (req.isAuthenticated())
return next();
else
res.redirect('/');
}
router.get('/home', ensureAuthenticated, function (req, res, next) {
res.send("OK");
})
迷上了
用户未定义
因为公式是这么写的,明白明白。好的,复制粘贴!
passport.use(new GitLabStrategy({
clientID: GITLAB_APP_ID,
clientSecret: GITLAB_APP_SECRET,
callbackURL: "http://localhost:3000/auth/gitlab/callback"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({gitlabId: profile.id}, function (err, user) {
return cb(err, user);
});
}
));
当尝试进行操作时,用户未定义且无法进行操作。关于此问题,请参考以下链接:https://github.com/auth0/passport-windowsauth/issues/37
发生无限的身份验证重定向循环。
var session = require('express-session');
・・・
app.use(passport.session());
如果不使用session,就无法有效地进行协作。
嗯?不需要认证就可以运行了…
拦截器?我本以为它会自动处理的,但它没有自动处理。
我必须为每个路径设置好才行!
※通常来说,是要扩展路由器的吧。
//認証チェック
function ensureAuthenticated(req, res, next) {
console.log("ensureAuthenticated");
if (req.isAuthenticated())
return next();//認証チェックしてから、次を呼び出すよ。
else
res.redirect('/');
}
router.get('/home', ensureAuthenticated, function (req, res, next) {
res.send("OK");
})
有点…不太像我想象中的画面。
OAuth就像是Google那样的验证机制,“我可以授予您权限吗?”的画面应该会出现,但实际并没有出现。
只是简单的登录页面。有点失望。
不过嘛,我就觉得这就是这样,就不去理它了。
首先,需要了解护照。
只有在这个基础上才能运行。passport-gitlab2只是OAuth服务提供商的库。
因此,首先需要了解passport如何工作。