| Tweet |
|
4,657 PVs |
Zend_Oauthを使ってOAuthコンシューマー(OauthConsumer.php)とOAuth認証用アクションコントローラー(OauthController.php)を実装していきます。Zend_Oauthを使うための環境設定などについては前編を参照してください。
Here I will show you how to implement an OAuth Consumer (OauthConsumer.php) and an action controller (OauthController.php) to authenticate user by using OAuth with Zend_Oauth. See also the previous post, sorry it is written in Japanese only, to setup your environment to use Zend_Oauth.
Zend_Oauth_Consumerクラス
本エントリ執筆時点では、Zend_Oauthはまだインキュベータとして開発中であり、Zend_Oauthのリファレンスガイドもまだ整備されていませんので、Zend_Oauthパッケージが提供するモジュールのうち、OAuthコンシューマー、OAuth認証用アクションコントローラーの実装で使用するZend_Oauth_Consumerクラスから簡単に紹介しておきましょう。Zend_Oauth_ConsumerはOAuthコンシューマーを実装したクラスです。Zend_Oauthクラスから派生しています。このチュートリアルでは以下の関数を使用します。
Zend_Oauth is still in incubator currently and its reference guide is not documented yet. At first, I will introduce to you Zend_Oauth_Consumer which will be used in both the OAuth Consumer and the action controller. Zend_Oauth_Consumer is derived from Zend_Oauth and provides features of the OAuth Consumer. The following functions provided by Zend_Oauth_Consumer are used in this tutorial.
__construct($options = null)
OAuthコンシューマーを構築します。引数$optionsには、OAuthコンシューマーの設定情報を格納した配列、またはZend_Configクラスを指定します。
Constructor. You can pass configuration for an OAuth Consumer to$optionsas either an array or a Zend_Config object.getRequestToken()
OAuthプロバイダーからリクエストトークンを取得して、Zend_Oauth_Token_Requestオブジェクトとして返します。(デフォルト引数は省略しています)
This function retrieves a Request Token from the OAuth Provider, and returns it as Zend_Oauth_Token_Request object. (Arguments passed by default are omitted here.)redirect()
OAuthプロバイダーからリクエストトークンを取得した後、OAuthプロバイダーのユーザー認証用URLへリダイレクトします。(デフォルト引数は省略しています)
After a Request Token is retrieved, this function redirects to an URL where the OAuth Provider authenticates a user. (Arguments passed by default are omitted here.)getAccessToken($queryData, Zend_Oauth_Token_Request $token)
OAuthプロバイダーからアクセストークンを取得して、Zend_Oauth_Token_Accessオブジェクトを返します。$queryDataには、OAuthコンシューマーのコールバックURLに渡されたクエリーストリングを指定します。$tokenには、getRequestToken()で取得したリクエストトークンを指定します。(デフォルト引数は省略しています)
This function retrieves an Access Token from the OAuth Provider, and returns it as Zend_Oauth_Token_Access object. You must give query string passed to callback URL of your OAuth Consumer to$queryData, and also give the Request Token which returned by getRequestToken() to$token. (Arguments passed by default are omitted here.)
OauthConsumerクラス
それでは、OAuthコンシューマーを実装したOauthConsumerクラスを紹介しましょう。
Let’t get started. The following shows you how to implement an OAuth Consumer with Zend_Oauth_Consumer.
require_once 'Zend/Oauth/Consumer.php';
require_once 'Zend/Session/Namespace.php';
class OauthConsumer
{
const DEFAULT_NAMESPACE = __CLASS__;
function __construct($config, $namespace=self::DEFAULT_NAMESPACE)
{
$this->consumer = new Zend_Oauth_Consumer($config);
$this->session = new Zend_Session_Namespace($namespace);
}
function requestAccessToken()
{
$token = $this->consumer->getRequestToken();
$this->session->request_token = serialize($token);
$this->consumer->redirect();
}
function getAccessToken(Zend_Controller_Request_Http $req)
{
if(!$req->isGet() || !isset($this->session->request_token))
{
return null;
}
$token = $this->consumer->getAccessToken(
$req->getQuery(),
unserialize($this->session->request_token)
);
unset($this->session->request_token);
return $token;
}
private $consumer;
private $session;
}
__construct($config, $namespace=self::DEFAULT_NAMESPACE)
OAuthコンシューマーと、リクエストトークンを保存するためのセッションを構築します。$configにはOAuthコンシューマーの設定情報を格納した配列、またはZend_Configクラスをしていします。前述のZend_Oauth_Consumerのコンストラクタ引数$optionsと同じです。$namespaceには、セッションの名前空間を指定します。デフォルトでは"OauthConsumer"が使われます。
Construct an OAuth Consumer and a session to store request token.$configis configuration for the OAuth Consumer as well as$optionsin the constructor of Zend_Oauth_Consumer described above. You can give a namespace of session to$namespace. If omitted, “OauthConsumer” will be used by default.requestAccessToken()
OAuthプロバイダーからリクエストトークンを取得して、OAuthプロバイダーのユーザー認証用URLへリダイレクトします。また、取得したリクエストトークンをセッションに保存します。
This function retrieves a Request Token from the OAuth Provider, and then redirects to the URL where the OAuth Provider autenticates a user. Also, the retrieved Request Token will be stored temporary in the session namespace.getAccessToken(Zend_Controller_Request_Http $req)
OAuthプロバイダーからアクセストークンを取得して、Zend_Oauth_Token_Accessオブジェクトを返します。$reqには、OAuthコンシューマーのコールバックURLの呼び出し時に生成されたリクエストオブジェクトを指定します。OAuthプロバイダーはリクエストトークンに基づいてアクセストークンを生成するため、getAccessToken()の呼び出しに先立って、requestAccessToken()が呼ばれていなければなりません。getAccessToken()は、requestAccessToken()内でセッションに一時保存されたリクエストトークンを利用しています。
This function retrieves an Access Token from the OAuth Provider, and returns it as Zend_Oauth_Token_Access object. You must give a request object$reqcreated by the request for callback URL of your OAuth Consumer. And you must call requestAccessToken() before calling this function, because the OAuth Provider generates an Access Token with the previous Request Token. Retrieving an Access Token from the OAuth Provider, this function uses the Request Token which is stored temporary in the session namespace by requestAccessToken().
OauthTwitterクラス
OAuth認証用のアクションコントローラーを実装したOauthControllerクラスの前に、OauthTwitterクラスを紹介しておきます。OauthTwitterはZend_Service_Twitterの派生クラスで、基本認証の代わりにOAuth認証を利用してTwitter APIにアクセスします。
Before implementing class OauthController which provides the action controller to authenticate user by using OAuth, let me show you class OauthTwitter which is derived from Zend_Service_Twitter and allows you to access to Twitter APIs with OAuth instead of HTTP basic authentication.
require_once 'Zend/Service/Twitter.php';
require_once 'Zend/Oauth/Token/Access.php';
class OauthTwitter extends Zend_Service_Twitter
{
function __construct(Zend_Oauth_Token_Access $token, array $config)
{
self::setHttpClient($token->getHttpClient($config));
parent::__construct(null);
}
}
OauthTwitterクラスでは、基底クラスZend_Service_Twitterのコンストラクタだけをオーバーライドしています。Zend_Service_Twitterが提供するすべてのpublicメソッドは、OauthTwitterでも同じように使うことができます。$tokenにはOAuthプロバイダーから取得したアクセストークンを、$configにはOAuthコンシューマーの設定情報を格納した配列を指定します。
OauthTwitter overrides only the constructor of parent class Zend_Service_Twitter, so that you can access to any public methods provided by Zend_Service_Twitter with an instance of OauthTwitter. $token is an Access Token retrieved from the OAuth Provider, and $config is an array which stores configuration for your OAuth Consumer.
OauthControllerクラス
前述したOauthConsumerクラス、OauthTwitterクラスを使って、OauthControllerクラスを実装していきましょう。
Then, I will show you class OauthController as an action controller with class OauthConsumer and class OauthTwitter.
require_once 'Zend/Config/Ini.php';
require_once 'Zend/Debug.php';
require_once '../models/OauthConsumer.php';
require_once '../models/OauthTwitter.php';
class OauthController extends Zend_Controller_Action
{
function init()
{
$this->config = new Zend_Config_Ini('../models/config.ini', 'twitter_oauth');
$this->oauth = new OauthConsumer($this->config);
$this->_helper->ViewRenderer->setNoRender();
}
function indexAction()
{
$this->oauth->requestAccessToken();
}
function callbackAction()
{
$token = $this->oauth->getAccessToken($this->getRequest());
$twitter = new OauthTwitter($token, $this->config->toArray());
$profile = $twitter->account->verifyCredentials();
if(!isset($profile->user))
{
throw Exception(isset($profile->error) ? $profile->error : "Couldn't verify credentials");
}
echo $profile->getIterator()->asXML();
}
private $config;
private $oauth;
}
/oauthにアクセスするとindexAction()が呼び出され、TwitterのOAuth認証ページにリダイレクトされます。
The function indexAction() is called when you access to /oauth, then you will be redirected to Twitter’s authentication page as below.

認証に成功すると、OAuthプロバイダーであるTwitterはOAuthコンシューマーのコールバックURL(/oauth/callback)にリダイレクトします。callbackAction()では、OAuthプロバイダーから取得したアクセストークンを使用して、Twitter APIのaccount/verifyCredentialsにアクセスし、認証したTwitterユーザーのプロフィール情報をXMLとして出力しています。
If you are successfully authenticated, Twitter as the OAuth Provider will redirect to the OAuth Consumer’s callback URL (/oauth/callback). The function callbackAction() access to the Twitter API account/verifyCredentials with an Access Token retrieved from the OAuth Provider, and displays the authenticated user’s profile as XML.
2010/6/21 at 18:56
大変参考になりました。
OauthControllerでタイプミスがありましたので報告です。
line24: $profile = $twitter->accountVerifyCredentials();
line30: echo $profile->getIterator()->asXML();
2010/6/22 at 19:58
lilyさん>
ご指摘ありがとうございます。30行目のタイプミスは修正いたしました。
24行目については、
$twitter->account->verifyCredentials()はマジックメソッド経由で、結果的に$twitter->accountVerifyCredentials()を呼び出すことになります。Zend Frameworkのドキュメントでも前者の形式でサンプルコードが載っています。