PassportはStrategyというオブジェクトを切り替えることで140以上の認証方法に対応したNode.jsのモジュールです。
今回はtwitter、facebookで認証の練習をしました。
Passportを使うための準備
環境は以下。カーネルが意外と古いです。
$ uname -a
Linux 2.6.32-358.11.1.el6.x86_64 #1 SMP Wed Jun 12 03:34:52 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
$ cat /etc/redhat-release
CentOS release 6.4 (Final)
Node.jsはインストールしている状態で以下でPassportをインストールします。
$ npm install passport
$ npm install passport-twitter
$ npm install passport-facebook
app.jsに以下を追加します。
var express = require('express')
  // other mod
  , passport = require('passport')
  , TwitterStrategy = require('passport-twitter').Strategy
  , FacebookStrategy = require('passport-facebook').Strategy; 
twitterで認証
TwitterDevでアプリ登録をします。
TWITTER_CONSUMER_KEYとTWITTER_CONSUMER_SECRETはメモっておきます。
まずはPassportのSetupです。
passport.serializeUser(function(user, done){
  done(null, user);
});
passport.deserializeUser(function(obj, done){
  done(null, obj);
});
passport.use(
  new TwitterStrategy({
  consumerKey: "yourCode", // TWITTER_CONSUMER_KEY
  consumerSecret: "yourCode",// TWITTER_CONSUMER_SECRET
  // callbackURLの指定
  callbackURL: "https://localhost:3000/auth/twitter/callback"
  }, function(token, tokenSecret, profile, done) {
    profile.twitter_token = token;
    profile.twitter_token_secret = tokenSecret;
    process.nextTick(function () {
      return done(null, profile);
    });
  })
);
profile.twitter_token = token;と代入しておくことでAPIを叩くときに参照できるようになります。
/auth/twitterにアクセスしたときに認証成功時に/index.html、失敗時に/loginにルーティングしています。
この辺の認証成功時、失敗時の処理の書き方が簡単ですね。
app.get("/auth/twitter", passport.authenticate('twitter'));
// Twitter callback Routing
app.get("/auth/twitter/callback", passport.authenticate('twitter', {
  successRedirect: '/index.html',
  failureRedirect: '/login'
}));
自分のアカウントで試しにログインしてみるとrequest.user.usernameに自分のIDが入っていることが確認できました。
app.get('/index.html', function(request, response) {
  console.log(request.user.username); 
  fs.readFile('public/index.html', 'UTF-8', function(err, data) {
  if (err) {
    return console.log(err);
  }
    response.writeHead(200, { 'Content-Type': 'text/html' });
    response.end(data);
  });
});
最初に/auth/twitterにアクセスしたときに以下のout-of-bandエラーで怒られました。
Desktop applications only support the oauth_callback value 'oob'
setting でCallback URLを指定できるのですがこれを書いてないのが原因みたいです。
facebookで認証
twitterでの認証と基本的に同様です。
App IDとApp Secretが必要です。
passport.use(
  new FacebookStrategy({
  clientID: "yourCode", 
  clientSecret: "yourCode",
  callbackURL: "https://localhost:3000/auth/Facebook/callback" 
  },function(accessToken, refreshToken, profile, done){
    passport.session.accessToken = accessToken; 
    process.nextTick(function(){
    done(null ,profile);
    });
  })
);
Passportは予想以上に簡単でした。これでまたNode.jsから離れられなくなる。
