omines / oauth2-gitlab
为 PHP League OAuth2-Client 提供的 GitLab OAuth 2.0 客户端提供程序
3.6.0
2023-11-06 21:46 UTC
Requires
- php: >=8.1
- league/oauth2-client: ^2.4.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.37.1
- guzzlehttp/psr7: ^2.6.1
- http-interop/http-factory-guzzle: ^1.2
- infection/infection: ^0.27.7
- m4tthumphrey/php-gitlab-api: ^11.12
- mockery/mockery: ^1.6.6
- php-http/guzzle7-adapter: ^1.0.0
- phpstan/extension-installer: ^1.3.1
- phpstan/phpstan: ^1.10.41
- phpstan/phpstan-mockery: ^1.1.1
- phpstan/phpstan-phpunit: ^1.3.15
- phpunit/phpunit: ^10.4.2
Suggests
- m4tthumphrey/php-gitlab-api: For further API usage using the acquired OAuth2 token
This package is auto-updated.
Last update: 2024-09-11 12:29:41 UTC
README
此软件包为 PHP League 的 OAuth 2.0 客户端提供 GitLab OAuth 2.0 支持。
安装
要安装,请使用 composer
composer require omines/oauth2-gitlab
使用方法
使用方法类似于基本的 OAuth 客户端,使用 \Omines\OAuth2\Client\Provider\Gitlab
作为提供者。
授权代码流
$provider = new \Omines\OAuth2\Client\Provider\Gitlab([ 'clientId' => '{gitlab-client-id}', 'clientSecret' => '{gitlab-client-secret}', 'redirectUri' => 'https://example.com/callback-url', 'domain' => 'https://my.gitlab.example', // Optional base URL for self-hosted ]); if (!isset($_GET['code'])) { // If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl(); $_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 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); // Use these details to create a new profile printf('Hello %s!', $user->getName()); } catch (Exception $e) { // Failed to get user details exit('Oh dear...'); } // Use this to interact with an API on the users behalf echo $token->getToken(); }
管理作用域
当创建您的 GitLab 授权 URL 时,您可以指定应用程序可能授权的状态和作用域。
$options = [ 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', 'scope' => ['read_user','openid'] // array or string ]; $authorizationUrl = $provider->getAuthorizationUrl($options);
如果没有定义,提供程序将使用内部默认值 'api'
。
执行 API 调用
安装 m4tthumphrey/php-gitlab-api
以在认证后与 Gitlab API 交互。手动连接或
$client = new \Gitlab\Client(); $client->setUrl('https://my.gitlab.url/api/v4/'); $client->authenticate($token->getToken(), \Gitlab\Client::AUTH_OAUTH_TOKEN);
在 GitlabResourceOwner
上调用 getApiClient
方法,这会隐式执行相同的操作。
贡献
有关详细信息,请参阅 CONTRIBUTING。
致谢
此代码是来自 官方 Github 提供程序 的修改分支,用于 Gitlab 使用,因此许多致谢应归功于 Steven Maguire。
法律
此软件是在荷兰埃因霍温的 Omines Full Service Internetbureau 内部开发的。它根据许可的 MIT 许可证与公众共享,不保证适用于任何特定目的。有关更多详细信息,请参阅包含的 LICENSE
文件。