如何将我的护照 js 凭据转发到 GitHub?
How do I forward my passport js credentials to GitHub?
我正在使用 passport.js 和 GitHub 策略来验证用户。我已经成功实现了用户登录,我可以在服务器上查询当前用户的凭据(req.user
)。
现在我希望能够在我的应用程序中使用 GitHub api。由于 CORS,我的设置是这样的:
User Action <-> GET / POST <-> My Web Server <-> GET / POST <-> GitHub
问题是我的 Web 服务器在代表用户向 GitHub 发出请求时需要传递用户的凭据。
我如何 "foward" 我的用户会话到 GitHub?
我在我的服务器上使用 superagent
来调用 GitHub API。
解决这个问题有两个部分。首先,您需要在 GitHub 触发回调时存储用户的访问令牌:
passport.use(new GitHubStrategy({
clientID: gitHubClientId,
clientSecret: gitHubClientSecret,
callbackURL: gitHubCallback
},
(accessToken, refreshToken, profile, cb) => {
cb(null, {accessToken, profile}); // Note that we serialize the access-token
}
));
接下来,您需要在对 GitHub 的请求中包含访问令牌。例如,要创建一个新的 Gist:
request.post('https://api.github.com/gists')
.set('Authorization', 'Token ' + req.user.accessToken) // This is the important bit!
.send(newGist)
.end((error, result) => {
console.log(error, result);
});
我正在使用 passport.js 和 GitHub 策略来验证用户。我已经成功实现了用户登录,我可以在服务器上查询当前用户的凭据(req.user
)。
现在我希望能够在我的应用程序中使用 GitHub api。由于 CORS,我的设置是这样的:
User Action <-> GET / POST <-> My Web Server <-> GET / POST <-> GitHub
问题是我的 Web 服务器在代表用户向 GitHub 发出请求时需要传递用户的凭据。
我如何 "foward" 我的用户会话到 GitHub?
我在我的服务器上使用 superagent
来调用 GitHub API。
解决这个问题有两个部分。首先,您需要在 GitHub 触发回调时存储用户的访问令牌:
passport.use(new GitHubStrategy({
clientID: gitHubClientId,
clientSecret: gitHubClientSecret,
callbackURL: gitHubCallback
},
(accessToken, refreshToken, profile, cb) => {
cb(null, {accessToken, profile}); // Note that we serialize the access-token
}
));
接下来,您需要在对 GitHub 的请求中包含访问令牌。例如,要创建一个新的 Gist:
request.post('https://api.github.com/gists')
.set('Authorization', 'Token ' + req.user.accessToken) // This is the important bit!
.send(newGist)
.end((error, result) => {
console.log(error, result);
});