6. PHPのライブラリ: thephpleague/oauth2-client
https://github.com/thephpleague/oauth2-client
$provider = new LeagueOAuth2ClientProviderGenericProvider([
'clientId' => 'demoapp', // The client ID assigned to you by the provider
'clientSecret' => 'demopass', // The client password assigned to you by the provider
'redirectUri' => 'http://example.com/your-redirect-url/',
'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize',
'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token',
'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
サンプルコードを上から見ていきましょう。
7. PHPのライブラリ: thephpleague/oauth2-client
$provider = new LeagueOAuth2ClientProviderGenericProvider([
'clientId' => 'demoapp', // The client ID assigned to you by the provider
'clientSecret' => 'demopass', // The client password assigned to you by the provider
'redirectUri' => 'http://example.com/your-redirect-url/',
'urlAuthorize' => 'http://brentertainment.com/oauth2/lockdin/authorize',
'urlAccessToken' => 'http://brentertainment.com/oauth2/lockdin/token',
'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);
リソース・認可サーバ設定は 3つのURL
8. PHPのライブラリ: thephpleague/oauth2-client
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
パラメータで分岐しながら処理をする。
(1) 最初のステップ
認証URL
認証URLへリダイレクト
リダイレクト先は Twitter などの認証画面
9. PHPのライブラリ: thephpleague/oauth2-client
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !==
$_SESSION['oauth2state'])) {
if (isset($_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
}
exit('Invalid state');
認可から帰ってきたときの処理。
まずはイレギュラーパターンの処理。
10. PHPのライブラリ: thephpleague/oauth2-client
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to PsrHttpMessageRequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'http://brentertainment.com/oauth2/lockdin/resource',
$accessToken
);
} catch (LeagueOAuth2ClientProviderExceptionIdentityProviderException$e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
(2) アクセストークンの取得
(3) リソース情報の取得
17. サーバのためのライブラリ: Doorkeeper
リソースデータを返すエンドポイント
ライブラリがほとんど処理してくれる。エンドポイントのコードは下のように作る。
module Api
class V1::ApiController < ::ApplicationController
def current_resource_owner
Member.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end
end
end
module Api
class V1::CredentialsController < V1::ApiController
before_action :doorkeeper_authorize!
def me
render json: { member: current_resource_owner }
end
end
end