grant-software / oauth2-grantid
为 The PHP League OAuth2-Client 提供的 GrantId OAuth 2.0 客户端提供者
dev-master
2018-06-14 15:49 UTC
Requires
- php: >=5.6.0
- league/oauth2-client: ^2.2.1
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-20 23:33:58 UTC
README
此包为 PHP League 的 OAuth 2.0 客户端(v2.0 及以上版本)提供 GrantId OAuth 2.0 支持。
安装
安装时使用 composer
composer require grant-software/oauth2-grantid
用法
用法与 The League 的 OAuth 2.0 客户端相同,使用 GrantId\OAuth2\Client\Provider\GrantId
作为提供者。
混合流程
此示例使用用户凭证检索授权码,以交换访问令牌。
if (!isset($_GET['code'])) { // If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl(); var_dump($authUrl); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authUrl); exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_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>"; // 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 Psr\Http\Message\RequestInterface. $request = $provider->getAuthenticatedRequest( 'GET', 'http://brentertainment.com/oauth2/lockdin/resource', $accessToken ); } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { // Failed to get the access token or user details. exit($e->getMessage()); } }
刷新令牌
要获取刷新令牌,您必须已请求带有 offline_access 范围的令牌。以下示例显示了如何使用提供者刷新令牌。
$provider = new GrantId\OAuth2\Client\Provider\GrantId([ 'clientId' => '{client-id}', 'clientSecret' => '{client-secret}', 'redirectUri' => 'https://mysite.com/callback', 'scopes' => '{scopes} offline_access', // Your subscription url 'authority' => 'https://sub.grantid.com' ]); $existingAccessToken = getAccessTokenFromYourDataStore(); if ($existingAccessToken->hasExpired()) { $newAccessToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $existingAccessToken->getRefreshToken() ]); // Purge old access token and store new access token to your data store. }