如何通过API发布主旨(不是匿名的)

我正在使用passport-github策略。

 passport.use(new Strategy({ clientID: "...", clientSecret: "...", callbackURL: 'http://localhost:3000/login/github/return', scope: 'gist' }, function(accessToken, refreshToken, profile, cb) { return cb(null, profile); })); 

然后我发出POST请求

 app.get('/profile/post', require('connect-ensure-login').ensureLoggedIn(), function(req, res){ var url = 'https://api.github.com/gists'; axios.post(url, { method: "POST", "description": "POSTING FROM EXPRESS", "public": true, "files": { "file1.txt": { "content": "EXPRESS " } } }) .then(function (response) {...}) .catch(function (error) { ... }); 

要点创造,但匿名。

我尝试传递"owner""user"作为请求参数的一部分,但没有用。 我也尝试在URL中传递用户名

据我所看到的文件没有提到这一点。

您必须存储您从Passport身份validationcallback中获得的访问令牌。 例如,使用mongo和mongoose来存储用户:

 passport.use(new GitHubStrategy({ clientID: "...", clientSecret: "...", callbackURL: 'http://localhost:3000/login/github/return' }, function(accessToken, refreshToken, profile, done) { process.nextTick(function() { User.findOne({ id: profile.id }, function(err, res) { if (err) return done(err); if (res) { console.log("user exists"); return done(null, res); } else { console.log("insert user"); var user = new User({ id: profile.id, access_token: accessToken, refresh_token: refreshToken }); user.save(function(err) { if (err) return done(err); return done(null, user); }); } }) }); } )); 

然后,当您反序列化用户时,用户将返回访问令牌:

 passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findOne({ "id": id }, function(err, user) { done(err, user); }); }); 

现在在你的端点中,把req.user.access_token放在github API请求的Authorization头里:

 app.get('/profile/post', require('connect-ensure-login').ensureLoggedIn(), function(req, res) { axios.post('https://api.github.com/gists', { "method": "POST", "description": "POSTING FROM EXPRESS", "headers": { "Authorization" : "token " + req.user.access_token }, "public": true, "files": { "file1.txt": { "content": "EXPRESS " } } }) .then(function (response) {...}) .catch(function (error) { ... }); } ); 

但是不是手动构build请求,你可以使用octonode库来为你做。 你可以在这里find一个带有octonode和mongodb的passport-github的完整例子

Interesting Posts