aptenex / oauth2-client-middleware
league/oauth2-client 的 OAuth2 PSR7 中间件
0.4.0
2020-08-27 14:05 UTC
Requires
- php: >=7.0.0
- beberlei/assert: ^3.2.0
- league/oauth2-client: ^1.2.0|^2.2.0
Requires (Dev)
- mockery/mockery: ^0.9.9
- phpunit/phpunit: ^4.0|^5.0
README
使用 league/oauth2-client 来通过 OAuth2 服务器进行请求认证的 PSR7 中间件。
安装
composer require somoza/oauth2-client-middleware
用法
当前实现间接依赖于 Guzzle 6,因为它直接依赖于 league/oauth2-client
。
使用 Guzzle
use Somoza\OAuth2Middleware\OAuth2Middleware; use Somoza\OAuth2Middleware\TokenService\Bearer; $stack = new \GuzzleHttp\HandlerStack(); $stack->setHandler(new CurlHandler()); $client = new \GuzzleHttp\Client(['handler' => $stack]); // instantiate a provider, see league/oauth2-client docs $provider = new GenericProvider( [ 'clientId' => 'your_client_id', 'clientSecret' => 'your_client_secret', 'urlAuthorize' => 'your_authorization_url', 'urlAccessToken' => 'your_access_token_url', 'urlResourceOwnerDetails' => 'your_resource_owner_url', ], [ 'httpClient' => $client ] // or don't pass it and let the oauth2-client create its own Guzzle client ); // attach our oauth2 middleware $bearerMiddleware = new OAuth2Middleware( new Bearer($provider), // use the Bearer token type [ // ignore (do not attempt to authorize) the following URLs $provider->getBaseAuthorizationUrl(), $provider->getBaseAccessTokenUrl(), ] ); $stack->push($bearerMiddleware); // if you want to debug, it might be useful to attach a PSR7 logger here
缓存访问令牌
可以将一个回调分配给中间件,以便将来使用保存访问令牌。请确保您了解存储访问令牌的安全性影响(自行承担风险)。
示例
use Somoza\OAuth2Middleware\OAuth2Middleware; use Somoza\OAuth2Middleware\TokenService\Bearer; use League\OAuth2\Client\Token\AccessToken; // see previous example for initialization $tokenStore = new EncryptedCache(); // you can use whatever you want here $token = null; if ($tokenStore->contains($userId)) { $tokenData = json_decode($cache->fetch($userId)); $token = new AccessToken($tokenData); } $bearerMiddleware = new OAuth2Middleware( new Bearer( $provider, // defined as in the "Usage" example $token, function (AccessToken $newToken, AccessToken $oldToken) use ($tokenStore, $userId) { // called whenever a new AccessToken is fetched $tokenStore->save($userId, $newToken->jsonSerialize()); } ), ); $stack->push($bearerMiddleware);
许可证
MIT - 查看 LICENSE.md