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);
    }
}

Posted 2012.09.01, 23:13 by mera and filed in Catalyst, OAuth
Catalyst で Google の OAuth を使う はコメントを受け付けていません
2012.08.18

Catalyst で Facebook の OAuth を使う

ライブラリを使わずにやりたかったので、PerlでOAuth 2.0を使ってみた を参考にした。
こちらのページの Plack::Request, Plack::Response を使わずに、Catalyst の $c->res を使った感じ。

http://localhost:3000/auth というページが Facebook Developers の Site URLに登録してあるとする。
/auth というパスに処理を作るため、
 $ perl script/hello_create.pl controller Auth
で Controller を作り、lib/Hello/Controller/Auth.pm を編集する。

1: Facebookページにリダイレクトして、Facebookにログインし、このアプリのアクセスを許可する
2: $redirect_uri に codeパラメータ付きで戻ってくる
3: token を取得するため、codeパラメータを使用して再び Facebook API にアクセスする
4: その token を使用すると、Facebookのその人の情報にアクセスできる

sub index : Path :Args(0) {
    my ( $self, $c ) = @_;

    my $app_id = '(Facebook Developers の App ID)';
    my $app_secret = '(Facebook Developers の App Secret)';
    my $authz_endpoint = 'https://www.facebook.com/dialog/oauth';
    my $token_endpoint = 'https://graph.facebook.com/oauth/access_token';
    # Facebook Developers の Website with Facebook Login の Site URL
    my $redirect_uri = 'http://localhost:3000/auth';

    # 2) get authorization code
    if ( my $code = $c->req->param('code') ) {

        # 3) get access token
        my $uri = URI->new($token_endpoint);
        $uri->query_form(
            client_id     => $app_id,
            client_secret => $app_secret,
            redirect_uri  => $redirect_uri,
            code          => $code
        );
        my $ua     = LWP::UserAgent->new;
        my $r      = $ua->get($uri);
        my %params = ();
        for my $pair ( split( /&/, $r->content ) ) {
            my ( $key, $value ) = split( /=/, $pair );
            $params{$key} = $value;
        }
        my $token = $params{access_token};

        # 4) get protected resources
        if ($token) {
            my $url = 'https://graph.facebook.com/me/friends';
            (略)
            $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(
            client_id    => $app_id,
            redirect_uri => $redirect_uri,
        );
        $c->res->redirect($uri);
    }
}

理解のため全コードを Controller に書いてるけど、実際に使うんだったらうまいことキレイにすべし。


Posted 2012.08.18, 23:59 by mera and filed in Catalyst, OAuth
2012.08.18

Ruby on Rails で Facebook の OAuth を使う

Ruby on RailsでfacebookのOAuth認証を実装する を参考にした。
facebook_oauth プラグインを使ってラクしたものだ。

gem のインストール
$ sugo gem install oauth
$ sugo gem install oauth2
$ sudo gem install facebook_oauth

バージョンを指定せずに最新をインストールして大丈夫だった。
oauth v0.4.6
oauth2 0.8.0
facebook_oauth 0.3.0

ソースコードの編集
$ rails generate controller Users index callback

– controller/users_controller.rb

class UsersController < ApplicationController
   CALLBACK_URL = "Facebook Developers の Website with Facebook Login の Site URL"
   CONSUMER_KEY = "Facebook Developers の App ID"
   CONSUMER_SECRET = "Facebook Developers の App Secret"
   
   def index
   end
   
   def oauth
     client = FacebookOAuth::Client.new(
       :application_id => CONSUMER_KEY,
       :application_secret => CONSUMER_SECRET,
       :callback => CALLBACK_URL
     )
     redirect_to client.authorize_url
   end

  def callback
     @client = FacebookOAuth::Client.new(
         :application_id => CONSUMER_KEY,
         :application_secret => CONSUMER_SECRET,
         :callback => CALLBACK_URL
      )
      @client.authorize(:code => params[:code])
   end
end

– views/users/index.html.erb
<%= link_to 'OAuth認証', '/users/oauth' %>

– views/users/callback.html.erb
<%= @client.me.info %>

以上は書いてあったとおり。

追加で以下の作業が必要。
– config/routes.rb

get "users/oauth"

Routing Error : No route matches [GET] “/users/oauth” が出たので追加してみた。

– Gemfile

gem 'facebook_oauth'

NameError : uninitialized constant UsersController::FacebookOAuth が出たので追加してみた。
ただ、facebook_oauth が Heroku にないのか、Heroku の git にあげようとするとエラーになるという問題が・・・


Posted 2012.08.18, 19:46 by mera and filed in OAuth, Rails
Ruby on Rails で Facebook の OAuth を使う はコメントを受け付けていません