ruby で mixi OpenID を呼ぶには

なかば自分用メモ。まあ要は ruby-openid の TIPS。


ruby-openid を使おう。

gem install ruby-openid


mixi OpenIDSSL 接続なので Net::HTTP の ca_file に証明書を設定せなあかんわけだが*1ruby-openidOpenID.fetcher.ca_file に突っ込んどくとそれを使ってくれる。
初期化のどこかのタイミングで下記のように CA 証明書のパスを指定しとけばOK。
ちなみにこれをサボると "OpenID: WARNING: making https request to https://mixi.jp/xrds_signon.pl?xxxxx without verifying server certificate; no CA path was specified." のようなワーニングが出る。

  OpenID.fetcher.ca_file = '/usr/share/ssl/cert.pem'


認証時に mixi でのニックネームがもらえるけど、SREG で「ニックネーム欲しいよ!」とあらかじめ要求しておかないと、くれない。

  # request of OpenID Authantication

  # prepare appropriate session and store
  consumer = OpenID::Consumer.new(session, store)
  openid = consumer.begin("https://id.mixi.jp/community/3609987")  # mixi community authantication

  sreg = OpenID::SReg::Request.new
  sreg.request_fields(['nickname'], true)  # we want user's nickname!!!
  openid.add_extension(sreg)

  redirect_url = openid.redirect_url(realm, return_url)  # redirect to this url


マイミクシィ認証やコミュニティ認証をすると、Claimed Identifier がそれぞれ特殊な URI になる。
ユーザ自身を表す OpenID URI が欲しいよ! という時は OP-Local Identifier にそれが入ってるんだが、 ruby-openid では Response.endpoint.local_id から取り出せる。

  # response of OpenID Authantication

  consumer = OpenID::Consumer.new(session, store)
  res = consumer.complete(params, current_url)

  claimed_id = res.identity_url # in case of community auth, "https://id.mixi.jp/community/3609987/01234567"
  id = res.endpoint.local_id # user's openid uri
  
  sreg = OpenID::SReg::Response.from_success_response(res)
  nickname = sreg.data["nickname"] # user's nickname

*1:Warningをシカトする手もあるが精神衛生上悪い……し、なりすまし防止のためにせっかくSSLになっているのが台無し