2012.09.01
Catalyst で Google の OAuth を使う
ホントはSAMLをやりたかったんだけど、Google::SAML::Response の使い方はわからないし、
ライブラリを使わないでやるのはますますわからないので、いったん置いとく。
OAuthは前に Facebook のをやったときと、ほとんど同じ。
本家サイトを見てできた。
API Console からAPI を使用するためのキーを取得する。
Product name を適当に登録し、Client ID, Client secret, Redirect URIs を使うのでメモする。
sub index : Path :Args(0) { my ( $self, $c ) = @_; my $app_id = '(API Console の Client ID)'; my $app_secret = '(API Console の Client secret)'; my $authz_endpoint = 'https://accounts.google.com/o/oauth2/auth'; my $token_endpoint = 'https://accounts.google.com/o/oauth2/token'; my $redirect_uri = 'http://localhost:3000/google'; # Redirect URIs # 2) get authorization code if ( my $code = $c->req->param('code') ) { # 3) get access token my $post_params = { client_id => $app_id, client_secret => $app_secret, redirect_uri => $redirect_uri, grant_type => "authorization_code", code => $code }; my $request = POST($token_endpoint, $post_params); my $ua = LWP::UserAgent->new; my $r = $ua->request($request); my $data = decode_json($r->content()); my $token = $data->{access_token}; # 4) get protected resources if ($token) { my $url = 'https://www.googleapis.com/oauth2/v1/userinfo'; (略) $c->response->body($html); } else { $c->response->body('fail to get token'); } } else { # 1) redirect to authorization endpoint my $uri = URI->new($authz_endpoint); $uri->query_form( response_type => 'code', client_id => $app_id, redirect_uri => $redirect_uri, scope => 'https://www.googleapis.com/auth/userinfo.profile' ); $c->res->redirect($uri); } }