Passport-twitterでTwitterの1.1のAPIを叩く
おはようございます。先日、息子がいたずらして、朱肉をいじって、 手が真っ赤になったところ、痛いよーと脅したら、効果がありすぎて 泣きじゃくってしばらく立ち直りませんでした。次の日の登園時にも 自分の手をみて思い出したようで、半べそになってました。@kjunichiです。
ちなみに
この記事書いていた頃のモジュールだと、OAuth周りで1.0のAPIを使っていてNGでしたが、 最近のものは1.1に対応したようです。
1.0が廃止になる予定が延びたものの
Node.jsの認証?ライブラリのPassportが便利という記事を読み 試してみたのですが、Twitterの認証はすんなり出来たのですが、 その後のAPIを叩く所でハマったのでそのメモです。 exampleからの変更点のメモになります。
Twitterストラテジーを保持し、トークン、トークンシークレットを保存
var ts = new TwitterStrategy({ consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, callbackURL: "https://afternoon-ridge-9228.herokuapp.com/auth/twitter/callback" }, function(token, tokenSecret, profile, done) { // asynchronous verification, for effect... // トークンとトークンシークレットをユーザ情報の中に入れて、API叩く際にこれを参照する。 profile.twitter_token = token; profile.twitter_token_secret = tokenSecret; process.nextTick(function () { // To keep the example simple, the user's Twitter profile is returned to // represent the logged-in user. In a typical application, you would want // to associate the Twitter account with a user record in your database, // and return that user instead. return done(null, profile); }); } ); passport.use(ts);
APIを叩く
上で保持しておいたtsでts._oauthでoauthモジュールにアクセスできるんです。
// search tweets. ts._oauth.getProtectedResource( 'https://api.twitter.com/1.1/search/tweets.json?q='+keyword, 'GET', req.user.twitter_token, req.user.twitter_token_secret, function (err, data, response) { console.dir(req.user); if(err) { res.send(err, 500); return; } //console.dir(data); var jsonObj = JSON.parse(data); res.render('search', { user: req.user, result: jsonObj }); });
関連記事
- GAE/JでTwitter APIを使う 昔はBasic認証も使えたそんな時代もあったんですね。
- Julia言語でTwitterのAPIを叩いてみた