如何正确使用passport-oauth2来使用Twitter Oauth2身份验证服务?

时间:2015-10-19 19:51:17

标签: twitter oauth oauth-2.0 passport.js

由于 passport-twitter 仍然适用于OAuth v1,我决定尝试使用 passport-oauth2 来完成Twitter登录,并为我的应用完成会话。

这就是我的尝试:

passport.use(new OAuth2Strategy({
    authorizationURL: 'https://api.twitter.com/oauth/authenticate',
    tokenURL: 'https://api.twitter.com/oauth/access_token',
    clientID: process.env.TWITTER_FINALCUT_CONSUMER_KEY,
    clientSecret: process.env.TWITTER_FINALCUT_CONSUMER_SECRET,
    callbackURL: 'http://localhost:9248/auth/login/redirect/tw'
    },
    function (access_token,refreshToken,profile,done) {
        console.log(accessToken,Object.keys(profile));
        return done(null, profile, {tokens: {accessToken: accessToken, refreshToken: refreshToken}});
}));

但是当到达启动身份验证过程的网址时,我会被重定向到此Twitter屏幕。我无法弄清楚我在做什么是错的。

有什么建议吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

基本上,策略与例如 https://github.com/Slotos/passport-reddit/blob/master/lib/passport-reddit/strategy.js

问题不在于Passport JS本身,而在于底层模块" node-oauth"。所以请特别注意"为了遵守我们正在采取压倒性的"评论上面的策略。

我希望它能在模块中修复,所以我只是在这里评论:https://github.com/ciaranj/node-oauth/issues/300

如果解决了这个问题,我想将其作为OAuth2策略直接贡献给Twitter策略。

推特的最重要步骤基本上是[现在,直到上面解决]:

var querystring = require('querystring');
var OAuth2 = require('oauth').OAuth2;
OAuth2.prototype.getOAuthAccessToken = function(code, params, callback) {
  var params= params || {};
  params['client_id'] = this._clientId;
  params['client_secret'] = this._clientSecret;
  var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code';
  params[codeParam]= code;

  var post_data= querystring.stringify( params );
  var post_headers= {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  };
  if (params.hasOwnProperty('headers') && typeof params.headers === 'object') {
    for (var key in params.headers) {
      post_headers[key] = params.headers[key];
    }
  }

  this._request("POST", this._getAccessTokenUrl() || 'https://api.twitter.com/oauth2/token' /* TODO */, post_headers, post_data, null, function(error, data, response) {
    if( error )  callback(error);
    else {
      var results;
      try {
        // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07
        // responses should be in JSON
        results= JSON.parse( data );
      }
      catch(e) {
        // .... However both Facebook + Github currently use rev05 of the spec
        // and neither seem to specify a content-type correctly in their response headers :(
        // clients of these services will suffer a *minor* performance cost of the exception
        // being thrown
        results= querystring.parse( data );
      }
      var access_token= results["access_token"];
      var refresh_token= results["refresh_token"];
      delete results["refresh_token"];
      callback(null, access_token, refresh_token, results); // callback results =-=
    }
  });
}

可以在战略中使用

var s64 = new Buffer(
  [encodeURIComponent(process.env.CONSUMER_KEY),':',
  encodeURIComponent(process.env.CONSUMER_SECRET)].join('')
).toString('base64');
OAuth2.prototype.getOAuthAccessToken('', {
  grant_type: 'client_credentials',
  headers: {
    Authorization: ['Basic', s64].join(' ')
  }
},
function(e, access_token, refresh_token, res) {
  console.log(e, access_token, refresh_token, res);
});