我如何将护照js凭证转发给GitHub?

我正在使用passport.js与GitHub策略来validation用户。 我已经成功实现了用户login,并且可以查询服务器上当前用户的凭证( req.user )。

现在我想能够从我的应用程序中使用GitHub api。 由于CORS,我的设置是这样的:

 User Action <-> GET / POST <-> My Web Server <-> GET / POST <-> GitHub 

问题是我的Web服务器需要在代表他们向GitHub发送请求时传递用户凭据。

我如何“前进”我的用户会话到GitHub?

我在我的服务器上使用superagent来调用GitHub API。

有两个部分来解决这个问题。 首先,当GitHub触发callback时,您需要存储用户的访问令牌:

 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的请求中。 例如,要创build一个新的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); });