簡體   English   中英

使用返回的令牌訪問github API

[英]Using the returned token to access github api

我在我的應用程序中使用了passportjs和passport-github來創建社交登錄名,

passport.use(new GithubStrategy(
  {
    clientID     : configAuth.githubAuth.clientID,
    clientSecret : configAuth.githubAuth.clientSecret,
    callbackURL  : configAuth.githubAuth.callbackURL
  },
  function(token, refreshToken, profile, done) {
    process.nextTick(function() {
      User.findOne({'github.id' : profile.id}, function(err, user) {
        if (err) {
          return done(err);
        }
        if (user) {
          return done(null, user);
        } else {
          var newUser = new User();
          newUser.github.id = profile.id,
          newUser.token     = token,
          newUser.name      = profile.displayName;
          newUser.email     = profile.emails[0].value;
          newUser.username  = profile.username;
          // save
          newUser.save(function(err){
            if (err) {
              throw err;
            }

            return done(null, newUser);
          });
        }
      });
    });
  }
));

現在,我正在使用另一個名為octonode的組件,該組件需要一個access_token來驗證其用戶,該回調中的令牌與此access_token相同,因為這樣做時我似乎不像是通過身份驗證的:

var github = require('octonode');

exports.read = function (req, res, next) {

  var client = github.client();
  client.get('/user?access_token=' + req.user.token, {}, function (err, status, body, headers) {
    res.json(body);
  });
};

並且也嘗試這樣做:

var client = github.client(req.user.token);
client.get('/user',{}, function...)

我出現黑屏,表示沒有反應。

好吧,作為SO中的一個答案指出:

請注意,Passport不會主動使用訪問令牌或刷新令牌,只能在登錄期間獲取用戶配置文件。 當需要進行任何API請求時,您負責由應用程序使用這些令牌。 這樣,您可以實現您描述的任何一種方法,過程中不涉及Passport。

access_tokens返回給您,但是之后不會處理,您是負責保存它或做任何您想做的人。

我的代碼基本上是受Scotch.io使用護照的facebook auth中的教程的啟發。 在那里,他們不需要每次登錄都更新令牌,因為他們不需要在教程中,但是他們確實將令牌保存在數據庫中,請檢查其源代碼。

在進行一些注釋和調試的過程中,我發現這是我的應用程序中的罪魁禍首,因此我需要更新條件(指出是否已找到用戶),更新令牌和一些值,以便一些重要信息在登錄時仍然存在。

if (user) {
   user.token = token;
   user.name  = profile.displayName;
   user.email = profile.emails[0].value;
   user.save();
   return done(null, user);
}

現在,這可以解決:

var client = github.client(req.user.token);
client.get('/user', {}, function (err, status, body, headers) {
    res.json(body);
});

感謝@MikeSmithDev幫助我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM