如何使用passportjs进行身份验证后对数据进行oauth请求?

时间:2016-05-07 15:19:52

标签: node.js authentication twitter oauth passport.js

我正在尝试创建一个NodeJS应用程序,从Twitter用户配置文件中提取数据,例如获取关注者,发布推文,aso。 为了验证应用程序,我使用了passport-js提供的身份验证方法(twitter策略):http://passportjs.org/

身份验证策略是通过为Twitter身份验证创建策略,然后使用此策略通过twitter进行身份验证来完成的,请按以下方式进行:

// =========================================================================
// TWITTER LOGIN =================================================================
// =========================================================================
passport.use(new TwitterStrategy({
    consumerKey     : twitterAuth.consumerKey,
    consumerSecret  : twitterAuth.consumerSecret,
    callbackURL     : twitterAuth.callbackURL,
    passReqToCallback : true, // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, tokenSecret, profile, done) {
// User.findOne won't fire until we have all our data back from Twitter
    process.nextTick(function() {

        // check if the user is already logged in
        if (!req.user) {
          console.log("Twitter Check if user is already logged in");

        User.findOne({ 'twitter.id' : profile.id }, function(err, user) {

            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
                return done(err);

            // if the user is found then log them in
            if (user) {
              console.log("Twitter User has been found log him in");
              // if there is a user id already but no token (user was linked at one point and then removed)
                    // just add our token and profile information
                    if (!user.twitter.token) {
                      console.log("Twitter, user was linked and then removed, add back token");
                      user.twitter.id    = profile.id;
                      user.twitter.token = token;
                      user.twitter.tokenSecret = tokenSecret;
                      user.twitter.username  = profile.username;
                      user.twitter.displayName = profile.displayName;

                        user.save(function(err) {
                            if (err)
                                throw err;
                            return done(null, user);
                        });
                    }

                return done(null, user); // user found, return that user
}));

// ==============================

在此之后我可以使用这样的策略进行身份验证:

    // =====================================
// TWITTER ROUTES ======================
// =====================================
// route for twitter authentication and login
app.get('/auth/twitter', passport.authenticate('twitter'));

// handle the callback after twitter has authenticated the user
app.get('/auth/twitter/callback',
    passport.authenticate('twitter', {
        successRedirect : '/dashboard',
        failureRedirect : '/'
    }));

身份验证工作正常,我从用户收到令牌和tokensecret,并可以将其保存在我的会话中。但是,现在我想做其他请求,例如为用户获取关注者和发布等,但我真的不明白如何做到这一点。

我可以使用oauth而不使用passportJS这些行,这里没有任何问题做推文,例如:

// Authentication using oauth for Twitter
var username = 'user';

var oa = require('oauth').OAuth();

oa = new OAuth("https://api.twitter.com/oauth/request_token",
             "https://api.twitter.com/oauth/access_token", 
             "consumerkey", "consumersecret", 
             "1.0A", "http://localhost:3000/oauth/authenticate", "HMAC-SHA1");

var access_token= "access_token";
var access_token_secret= "access_token_secret";

// Test if user has been authenticated
oa.get("https://api.twitter.com/1.1/users/show.json?screen_name=" + user, access_token, access_token_secret, function(error, data) {
if (!error)
 console.log(data); 
else 
     console.log("An error has occurred while authentication of the user: " + error);
});

console.log("Twitter-API Successfully Loaded");

// Use Oauth to post a tweet
// Tweet a post update 
router.post('/post-tweet/', function (req, res) {

oa.post("https://api.twitter.com/1.1/statuses/update.json?status=" + req.body.tweet, access_token, access_token_secret, {}, "", function(error, data) {

  if (!error && res.statusCode == 200){
      res.send("Successfully tweeted an update");  
  }

  else {
      res.send("Failure to tweet a new post: " + JSON.stringify(error));
  }
});
});

所以基本上我的问题是现在,我如何使用passportJS做同样的事情???我不明白如何从passportJS获得认证机制,以便能够向Twitter API发出GET或POST请求。

编辑: 我找到了我需要的护照对象并且可以访问它,但是,如何在twitter详细信息中检索_oauth对象?

以下是对象内容:

Authenticator {
_key: 'passport',
 _strategies: 
 { session: SessionStrategy { name: 'session' },
   'local-signup': 
    Strategy {
      _usernameField: 'email',
      _passwordField: 'password',
      name: 'local',
      _verify: [Function],
      _passReqToCallback: true },
   'local-login': 
    Strategy {
      _usernameField: 'email',
      _passwordField: 'password',
      name: 'local',
      _verify: [Function],
      _passReqToCallback: true },
   facebook: 
    Strategy {
      name: 'facebook',
      _verify: [Function],
      _oauth2: [Object],
      _callbackURL: 'http://localhost:3000/auth/callback',
      _scope: undefined,
      _scopeSeparator: ',',
      _key: 'oauth2:www.facebook.com',
      _stateStore: NullStore {},
      _trustProxy: undefined,
      _passReqToCallback: true,
      _skipUserProfile: false,
      _profileURL: 'https://graph.facebook.com',
      _profileFields: [Object],
      _enableProof: undefined,
      _clientSecret: '012345' },
   twitter: 
    Strategy {
      name: 'twitter',
      _verify: [Function],

     >> _oauth: [Object],  I would need this object here 

      _userAuthorizationURL: 'https://api.twitter.com/oauth/authenticate',
      _callbackURL: 'http://localhost:3000/auth/twitter/callback',
      _key: 'oauth:twitter',
      _requestTokenStore: [Object],
      _trustProxy: undefined,
      _passReqToCallback: true,
      _skipUserProfile: false,
      _userProfileURL: 'https://api.twitter.com/1.1/account  /verify_credentials.json',
      _skipExtendedUserProfile: false,
      _includeEmail: false,
      _includeStatus: true,
      _includeEntities: true } },
_serializers: [ [Function] ],
_deserializers: [ [Function] ],
_infoTransformers: [],
_framework: 
 { initialize: [Function: initialize],
   authenticate: [Function: authenticate] },
_userProperty: 'user',
Authenticator: [Function: Authenticator],
Passport: [Function: Authenticator],
Strategy: { [Function: Strategy] Strategy: [Circular] },
strategies: { SessionStrategy: { [Function: SessionStrategy] super_:   [Object] } } }

1 个答案:

答案 0 :(得分:1)

好吧我修好了:))

对于遇到同样问题的人,访问护照中的oauth的方法是: passport._strategies.twitter._oauth.post(某些行动){ }