先日、待望の Mixi OpenID がリリースされました。
id:ZIGOROu さんのところで、くわしく解説されていますが、Mixi OpenIDでは、sreg(OpenID Simple Registration Extension)と呼ばれる OpenID に付随するユーザのプロフィールをやりとりするためのプロトコルを使って、Mixi で使われるニックネームを取得することができます。
sreg の仕様は、OpenID Simple Registration Extension 1.0や、ここを参照してください。ぼくはこんがらがってしまい、ちゃんと理解できませんでした。。
仕様を完全に理解しなくても(理解するべきでしょうが)、Rails の Open ID Authentication を使って、簡単にニックネームを取得することができました。
下記は open_id_authentication の README ファイルにあった、sreg 取得方法の例をちょっとだけ変えたものです。open_id_authentication メソッドは、identity_url (ex. https://mixi.jp, http://profile.livedoor.com/****)を引き取り、OP にパラメータを組み立てて認証を行うメソッドのようです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | def open_id_authentication(identity_url) # Pass optional :required and :optional keys to specify what sreg fields you want. # Be sure to yield registration, a third argument in the #authenticate_with_open_id block. authenticate_with_open_id(identity_url, :optional => :nickname) do |status, identity_url, registration| case status when :missing failed_login "Sorry, the OpenID server couldn't be found" when :canceled failed_login "OpenID verification was canceled" when :failed failed_login "Sorry, the OpenID verification failed" when :successful if @current_user = @account.users.find_by_identity_url(identity_url) @current_user.nickname = registration["nickname"] if current_user.save successful_login else failed_login "Your OpenID profile registration failed: " + @current_user.errors.full_messages.to_sentence end else failed_login "Sorry, no user by that identity URL exists" end end end end |
authenticate_with_open_id メソッドに :options => :nickname としているところが(5行目)、sreg を用いてニックネームを取得する宣言です。コメントにあるとおり、sreg を用いる際には、status, identity_url に加え、3つめの変数である regsitration を与える必要があります。
この registration にハッシュ形式で sreg 情報が返ってくるようなので、15行目のように nickname を取り出し、RP である自分のアプリのニックネームとして入れてあげています。
open_id_authenticationプラグインを用いることで簡単に取得することができましたが、もういちど sreg の仕様などを読んで理解を深めたいと思います。

