ゼロから学ぶOAuth
第4回 OAuth Service Providerの実装
最終回となる今回は,OAuth Service Providerの実装方法について,手順を追って解説します。
OAuth Service Providerがすべきこと
OAuth連載最終回は,OAuth Service Providerの実装を行います。Service Providerの役割は,大きく以下の3つに分けられます。
- OAuth Consumerの管理
- OAuth Request / Access Tokenの管理
- OAuth経由のリソースへのアクセス管理
Rails OAuth Pluginを用いたOAuth Service Providerの実装
Railsではruby-oauth gemとOAuth Pluginを用いることで,簡単にOAuth Service Providerを実装することができます。以下実装手順です。
ruby-oauth gemのインストール(まだの場合)
gem install oauth
Railsアプリケーション作成およびpluginインストール
rails service_provider
cd service_provider
./script/plugin install git://github.com/pelle/oauth-plugin.git
ControllerおよびModel生成
./script/generate oauth_provider
これで以下のContorollerおよびModelが生成されます。
app/controllers/oauth_controller.rb
app/models/oautht_token.rb
app/models/access_token.rb
app/models/request_token.rb
app/models/client_application.rb
app/models/oauth_nonce.rb
最後にroutesとassociationを設定して,db:migrateを実行します。なおOAuth PluginはUserモデルおよびcurrent_user,login_requiredメソッドの存在を前提にしています。必要があれば適宜該当箇所を編集してください。
リスト:routes.rb
map.oauth '/oauth',:controller=>'oauth',:action=>'index'
map.authorize '/oauth/authorize',:controller=>'oauth',:action=>'authorize'
map.request_token '/oauth/request_token',:controller=>'oauth',:action=>'request_token'
map.access_token '/oauth/access_token',:controller=>'oauth',:action=>'access_token'
map.test_request '/oauth/test_request',:controller=>'oauth',:action=>'test_request'
assiciation (User model is required)
has_many :client_applications
has_many :tokens, :class_name=>"OauthToken",:order=>"authorized_at desc",:include=>[:client_application]
rake db:migrate
ここまでで前述のService Providerに(最低限)必要な機能はそろい,以下のbefore_filterが利用可能になります。
before_filter :login_or_oauth_required
before_filter :oauth_required
なおService Provider Sample - githubにもこれと同様のサンプルアプリケーションを公開していますので,適宜ダウンロードして動かしてみてください。


