hoanguyenmanh / oauth2-hydra
提供与 Hydra 兼容的 oauth2 客户端。
v0.1.0
2018-01-24 22:26 UTC
Requires
- league/oauth2-client: ^2.2
Requires (Dev)
- mockery/mockery: ^1.0
- phpunit/phpunit: ^6.5
This package is auto-updated.
Last update: 2024-09-25 23:25:35 UTC
README
此包为 PHP League 的 OAuth 2.0 客户端 提供了 Hydra OAuth 2.0 支持。
安装
要安装,请使用 composer
composer require hoanguyenmanh/oauth2-hydra
使用方法
使用方法与 The League 的 OAuth 客户端相同,使用 \Hydra\OAuth2\Provider\OAuth2
作为提供者。
使用 Hydra SDK
您可以使用此库获取用于与 Hydra SDK 一起使用的访问令牌。
这里我们获取了一个具有 'hydra.clients' 范围的令牌
$provider = new \Hydra\OAuth2\Provider\OAuth2([
'clientId' => 'admin',
'clientSecret' => 'demo-password',
'domain' => 'https://your-hydra-domain',
]);
try {
// Get an access token using the client credentials grant.
// Note that you must separate multiple scopes with a plus (+)
$accessToken = $provider->getAccessToken(
'client_credentials', ['scope' => 'hydra.clients']
);
} catch (\Hydra\Oauth2\Provider\Exception\ConnectionException $e) {
die("Connection to Hydra failed: ".$e->getMessage());
} catch (\Hydra\Oauth2\Provider\Exception\IdentityProviderException $e) {
die("Failed to get an access token: ".$e->getMessage());
}
// You may now pass $accessToken to the hydra SDK to manage clients
作为 OIDC 客户端
如果您是依赖方,也可以使用此库。
在这里,我们将用户发送到 Hydra 进行身份验证,以便我们完成授权码流程
$provider = new \Hydra\OAuth2\Provider\OAuth2([
'clientId' => 'admin',
'clientSecret' => 'demo-password',
'domain' => 'https://your-hydra-domain',
// Be sure this is a redirect URI you registered with Hydra for your client!
'redirectUri' => 'http://your-domain.com/bobsflowers',
]);
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl(['scope' => ['openid']]);
$_SESSION['oauth2state'] = $provider->getState();
header('Location: '.$authUrl);
die();
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
die('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
// $user contains public claims from the id token
printf('User info: ', json_encode($user));
} catch (\Hydra\Oauth2\Provider\Exception\IdentityProviderException $e) {
die('Unable to fetch user details: '.$e->getMessage());
}
// Use this to interact with an API on the users behalf
echo $token->getToken();
}