alphalabs / oauth2-client
PHP OAuth2 API 客户端。与 friendofsymfony/oauth2-php 规范兼容。
dev-master / 1.0.x-dev
2014-01-07 22:07 UTC
Requires
- php: >=5.3.3
- guzzle/guzzle: ~3.7
Suggests
- jms/serializer: Allows advance deserialization of response to target objects
This package is not auto-updated.
Last update: 2024-09-24 00:57:35 UTC
README
A PHP OAuth2 API client. Works well with friendofsymfony/oauth2-php specification
此库基于 Guzzle 构建,并添加了 OAuth2 认证机制,以实现安全且面向用户的 API 调用。
API 客户端遵循 OAuth2 规范,这些规范应用于 friendofsymfony/oauth2-php 库和 friendsofsymfony/oauth-server-bundle。
目前,该库提供以下功能
- Oauth2 透明认证:在初始资源请求中,如果需要,库将透明地请求访问令牌。
- 资源反序列化:可以向 API 客户端提供 JMS Serializer 的一个实例。因此,如果目标资源类与请求相关联,API 客户端将尝试将响应数据反序列化为目标对象。
安装
将库添加到您的 composer.json
文件中
"require": { "alphalabs/oauth2-client": "1.0@dev" }
别忘了使用 composer update
更新您的依赖关系
用法
首先创建一个实现 AlphaLabs\OAuth2Client\Model\Security\TokenManager
的类。此管理器将处理访问令牌在请求之间的持久化策略。
<?php namespace Foo\Bar; use AlphaLabs\OAuth2Client\Model\Security\Token; use AlphaLabs\OAuth2Client\Model\Security\TokenManager; class MyTokenManager implements TokenManager { public function getUserToken($clientName, $userId) { // Retrieve the token linked to the user (for user-oriented API calls). // It could be stored in a database, a cache file etc ... return $token; } public function getClientToken($clientName) { // Retrieve the token linked to the client (for client-oriented API calls). // It could be stored in a database, a cache file etc ... return $token; } public function save($clientName, Token $token) { // The type of token (user/client) could be determined with the userId attribute value: if ($token->getUserId()) { // This is a user-related token // Persists the token in a DB, a cache file etc... } else { // This is a client-related token // Persists the token in a DB, a cache file etc... } } }
然后,您可以实例化一个 API 客户端并开始请求 API
<?php namespace Foo\Bar; use AlphaLabs\OAuth2Client\OAuth2Client; class MyClass { public function foo() { $apiClient = new OAuth2Client( 'my_api_client' // Client name 'https://api.myproject.com', // Base API URL 'my_client_id', // The client ID (provided by the API) 'my_client_secret', // The client secret key (provided by the API) new MyTokenManager(), // Your custom token manager '/oauth/v2/token' // The URI used to requests access tokens ); $request = new ClientRequest('GET', '/ping'); // Optionally, an instance of the JMS Serialiser can be injected into the client in order to // get an object instead of an associative array: $apiClient->setSerializer(JMS\Serializer\SerializerBuilder::create()->build()); $request->setDeserializationTargetClass('\Foo\Bar\PingResource'); $pingResult = $apiClient->send(); } }
待定
- 更好的错误处理(基于 HTTP 状态码)
- 添加了从响应数据中检索响应信息(头信息、HTTP 状态码)的可能性
- (提出您的想法)
鸣谢
- Sylvain Mauduit (@Swop)
许可
MIT