2012.09.03

Catalyst で OpenID を使ってみる

参考にしたサイト
1. Consumerの実装を知り、OpenIDを使ってみよう
2. PerlでYahoo!とmixiのOpenIDを使ってみよう!

1. のサイトの通りにやったら、Error : signature_mismatch: Prior association invalidated ID provider response. というエラーが出たので、2. のサイトを参考にして、new のときのキャッシュ、debug パラメータを消した。

使用するOpenIDのCPANライブラリは、Net::OpenID::Consumer

cpan> install Net::OpenID::Consumer

で問題なく入る。

OpenID の処理へ飛ばすための場所と、結果が返ってくる場所の2つが必要。
前者が http://localhost:3000/openid, 後者が http://localhost:3000/openid/helper としてある。

http://localhost:3000/openid?openid_url=https://mixi.jp というURLをたたくと、OpenID の認証が始まる。

OpenID の処理へ飛ばすための場所(http://localhost:3000/openid)

use LWP::UserAgent;
use Net::OpenID::Consumer;

sub index : Private {
    my ( $self, $c ) = @_;

    my $csr = Net::OpenID::Consumer->new(
        ua => LWP::UserAgent->new,
        consumer_secret => 'hogehoge',
        args => $c->req->params,
    );

    if (my $cident = $csr->claimed_identity($c->req->params->{openid_url})) {
        $cident->set_extension_args('http://openid.net/srv/ax/1.0', {
            mode => 'fetch_request',
            'type.nickname' => 'http://axschema.org/namePerson/friendly',
            required => 'nickname',
        });
        my $check_url = $cident->check_url(
            return_to => "http://localhost:3000/openid/helper",
            trust_root => "http://localhost:3000/",
        );
        $c->res->redirect($check_url);
    }
    else {
        $c->res->body("Can't create claimed identifier object.");
    }
    $c->stash->{template} = "openid.t";
    $c->forward('Hello::View::TT');
}

結果が返ってくる場所(http://localhost:3000/openid/helper)

use LWP::UserAgent;
use Net::OpenID::Consumer;

sub index : Private {
    my ( $self, $c ) = @_;

    my $csr = Net::OpenID::Consumer->new(
        ua => LWP::UserAgent->new,
        consumer_secret => 'hogehoge',
        args => $c->req->params,
    );

    if (my $setup_url = $csr->user_setup_url) {
        $c->res->redirect($setup_url);
    }
    elsif (my $vident = $csr->verified_identity) { # ここで処理する
        my $ax = $vident->signed_extension_fields('http://openid.net/srv/ax/1.0');

        # ニックネームを取得する
        my $nickname = $c->req->params->{'openid.ax.value.nickname'};
        if(!($nickname)){$nickname = "匿名";}

        # ProfileのURLを取得する
        my $profile = $c->req->params->{'openid.identity'};

        $c->res->body("

" . $nickname . "さんがログインしました。

"); } elsif ($csr->user_cancel) { $c->res->body('Cancel'); } else { Catalyst::Exception->throw('Error : ' . $csr->err); } }

Posted 2012.09.03, 00:22 by mera and filed in Catalyst, OpenID
Catalyst で OpenID を使ってみる はコメントを受け付けていません
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

Catalyst インストール

会社では Catalyst を使ってるので、家マシンにも入れてみた。

Install Catalyst
1. sudo apt-get install build-essential
2. Ubuntuソフトウェアセンターから libcatalyst-perl をインストール
3. sudo perl -MCPAN -e ‘install Task::Catalyst’
(3でいろいろインストールされたので2が足りなかったのかもしれない)

あとは、
$ catalyst.pl Hello (Helloはプロジェクト名)
$ cd Hello/script
$ perl hello_server.pl

ついでに Eclipse で Perl を使えるようにEPICというプラグインを入れた。
http://www.epic-ide.org/updates/


Posted 2012.08.18, 20:40 by mera and filed in Catalyst
Catalyst インストール はコメントを受け付けていません