■プロジェクト
以下のコマンドでCakePHPをダウンロードして展開する。
wget https://github.com/cakephp/cakephp/tarball/master
tar xvzf cakephp-cakephp-2.1.3-1-g5270721.tar.gz
cd cakephp-cakephp-5270721
■Pluginの設置
面倒なのでプラグインを使う。
cd app/Plugin
git clone https://github.com/seddonmedia/cakephp-oauth-server.git OAuth
mv OAuth/Controller/OAuthController.php OAuth/Controller/OauthController.php #多分必要
oauth2-phpが必要になるので以下のコマンドを実行する。
cd app/Vendor
git clone https://github.com/quizlet/oauth2-php.git
■Schema
CREATE TABLE IF NOT EXISTS `access_tokens` (
`oauth_token` varchar(40) NOT NULL,
`client_id` char(36) NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`expires` int(11) NOT NULL,
`scope` varchar(255) DEFAULT NULL,
PRIMARY KEY (`oauth_token`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `auth_codes` (
`code` varchar(40) NOT NULL,
`client_id` char(36) NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`redirect_uri` varchar(200) NOT NULL,
`expires` int(11) NOT NULL,
`scope` varchar(255) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `clients` (
`client_id` char(20) NOT NULL,
`client_secret` char(40) NOT NULL,
`redirect_uri` varchar(255) NOT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `refresh_tokens` (
`refresh_token` varchar(40) NOT NULL,
`client_id` char(36) NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`expires` int(11) NOT NULL,
`scope` varchar(255) DEFAULT NULL,
PRIMARY KEY (`refresh_token`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
■ログイン
アプリケーションによって実装は様々だが、以下の変数にuniqueなユーザidを保持している必要がある。
$this->Auth->user('id');
以降はドキュメントに書いてあるので必要ないが一応。
■ルーティング
app/Config/bootstrap.phpの最終行に以下を追記する。
CakePlugin::loadAll(array(
'OAuth' => array('routes' => true)
));
■Client IDとClient Secretの取得
var_dump($this->OAuth->Client->add('http://sample.org'));
ここで取得できるのはクライアントID(a)とSecret(b)である。表示されるSecretは実際の値で、DB側に保存されている値はhash化されている。
■Authorization Codeの取得
/oauth/authorize?response_type=code&client_id=xxxx&redirect_url=http%3a%2f%2fsample.org
Authorization Codeが取得できる。(c)
■Access Tokenの取得
/oauth/token?grant_type=authorization_code&code=(c)&client_id=(a)&client_secret=(b)
Access Tokenの取得時に(b)は以下の部分でhash化してfindされる。
public function checkClientCredentials($client_id, $client_secret = NULL) {
$conditions = array('client_id' => $client_id);
if ($client_secret) {
$conditions = array(
'client_secret' => self::hash($client_secret),
);
}
$client = $this->Client->find('first', array(
'conditions' => $conditions,
'recursive' => -1
));
if ($client){
return $client['Client'];
};
return false;
}