germania-kg/authapi-client

该软件包最新版本(1.1.1)没有提供许可证信息。

德国认证API的HTTP客户端

1.1.1 2022-08-24 11:17 UTC

This package is auto-updated.

Last update: 2024-09-24 15:43:28 UTC


README

AuthApi客户端

用于从德国认证API(AuthApi)获取认证令牌的PHP客户端(服务端)。

安装

composer require germania-kg/authapi-client

接口和抽象类

AuthApiInterface

AuthApiInterface提供了三个公共方法

  • getToken,它需要用户名密码,并返回一个AuthToken实例,可选地带有长TTL(“刷新”)
  • login,它需要用户名密码,并返回一个AuthToken实例,通常带有短TTL。
  • refresh,它接受一个AuthToken实例,并返回一个新的AuthToken实例
<?php
namespace Germania\AuthApiClient;

interface AuthApiInterface
{
    public function getToken(string $username, string $password, bool refresh = false) : AuthTokenInterface;
    public function login(string $username, string $password) : AuthTokenInterface;
    public function refresh(AuthTokenInterface $token) : AuthTokenInterface;
}

AuthApiAbstract

抽象类AuthApiAbstract实现了AuthApiInterface,因此您必须使抽象方法生效。它们使用了本包中包含的Psr\Log\LoggerAwareTraitLoglevelTrait。因此,所有从AuthApiAbstract扩展的实例都可以

<?php
class MyClient extends AuthApiAbstract {
  	// Implement abstract methods here
}

$my_client = new MyClient;

// LoggerAwareTrait
$my_client->setLogger( new Monolog );

// LoglevelTrait
$my_client->setErrorLoglevel( \Psr\Log\LogLevel::ERROR) );
$my_client->setSuccessLoglevel( \Psr\Log\LogLevel::INFO) );
$my_client->setErrorLoglevel("error");  
$my_client->setSuccessLoglevel("info");

实现

使用Guzzle

GuzzleAuthApi客户端扩展了AuthApiAbstract并实现了AuthApiInterface。它使用GuzzleHttp Client在德国的AuthApi上进行认证。Guzzle客户端需要配置AuthAPI的base_uri

use Germania\AuthApiClient\GuzzleAuthApi;

// Setup dependencies
$guzzle = new \GuzzleHttp\Client(['base_uri' => "https://api.test.com/"]);

// Optional with PSR-3 Logger support.
$client = new GuzzleAuthApi( $guzzle);
$client = new GuzzleAuthApi( $guzzle, new Monolog);

设置Guzzle客户端

$guzzle = new \GuzzleHttp\Client( ... );
$client->setGuzzleClient($guzzle);  

使用PSR-18 HTTP客户端

HttpClientAuthApi扩展了抽象类AuthApiDecorator,因此也实现了AuthApiInterface

构造函数需要AuthApi的基础URL和一个PSR-18 客户端实例。可选的PSR-3 Logger可以作为第三个参数传递。

<?php
use Germania\AuthApiClient\HttpClientAuthApi;  

// Setup dependencies
$base_url = "https://api.test.com/";
$psr_18 = new \GuzzleHttp\Client;

// Optional with PSR-3 Logger support.
$client = new HttpClientAuthApi($base_url, $psr_18);
$client = new HttpClientAuthApi($base_url, $psr_18, new Monolog);

设置基础URL

$client->setBaseUrl("https://api.test.com/");

设置PSR-18 HTTP客户端

use GuzzleHttp\Client as Guzzle;
$client->setHttpClient( new Guzzle );

设置PSR-17 请求和流工厂

use Nyholm\Psr7\Factory\Psr17Factory;
$client->setRequestFactory( new Psr17Factory );
$client->setStreamFactory( new Psr17Factory );

PSR-6 缓存支持

CacheAuthApiDecorator是任何AuthApiInterface实例的PSR-6 Cache装饰器。它扩展了抽象类AuthApiDecorator,因此也实现了AuthApiInterface

构造函数需要AuthApiInterface实例和一个PSR-6 CacheItemPool。可选的PSR-3 Logger可以作为第三个参数传递。

use Germania\AuthApiClient\CacheAuthApiDecorator;
use Germania\AuthApiClient\GuzzleAuthApi;
use GuzzleHttp\Client as Guzzle;

// Setup dependencies
$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter;
$inner = new GuzzleAuthApi( new Guzzle );

// Optional with PSR-3 Logger support.
$client = new CacheAuthApiDecorator($inner, $cache);
$client = new CacheAuthApiDecorator($inner, $cache, new Monolog);

设置PSR-6 CacheItemPool

$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter;
$client->setCacheItemPool($cache); 

使用示例

此使用示例结合了上述AuthApi客户端。

AuthToken的生命周期通常非常短;为了获得一个具有更长TTL(即登录刷新)的令牌,请将第三个布尔参数传递给getToken方法。新的TTL从令牌生命周期中推导出来。

<?php
use Germania\AuthApiClient\CacheAuthApiDecorator;
use Germania\AuthApiClient\GuzzleAuthApi;

// Dependencies
$guzzle = new \GuzzleHttp\Client(['base_uri' => "https://api.test.com/");
$cache  = new \Symfony\Component\Cache\Adapter\FilesystemAdapter;
$logger = new \Monolog\Monolog( ... );
               
// AuthAPi clients                                  
$inner  = new GuzzleAuthApi( $guzzle, $logger);
$client = new CacheAuthApiDecorator($inner, $cache, $logger);

// Retrieve AuthToken, either short-living or long-TTL
$token = $client->getToken("username", "password");  
$token = $client->getToken("username", "password", (bool) "refresh");  

// Work with AuthToken
echo get_class($token);     // \Germania\AuthApiClient\AuthToken
echo $token;                // "somerandomstring"
echo $token->getContent();  // "somerandomstring"  
echo $token->getLifeTime(); // e.g. 60

异常处理

AuthApi客户端抛出的任何异常都实现了AuthApiExceptionInterface。因此,捕获\Germania\AuthApiClient\Exceptions\AuthApiExceptionInterface通常就足够了。

Guzzle客户端抛出的任何与请求相关的异常将被包装在AuthApiRequestException中。此异常类扩展了\RuntimeException并实现了AuthApiExceptionInterface

如果检索到的AuthApi响应有问题,将抛出AuthApiResponseException。此异常类扩展了\UnexpectedValueException并实现了AuthApiExceptionInterface

<?php
  
use Germania\AuthApiClient\Exceptions\{
  AuthApiRequestException,
  AuthApiResponseException,
  AuthApiExceptionInterface  
};

try {
	$token = $client->getToken("username", "password");  
}
catch (AuthApiRequestException $e) {
  $guzzle_exception = $e->getPrevious(); // Possibly previous Guzzle Exception
}
catch (AuthApiResponseException $e) {
  $json_error = $e->getPrevious(); // Possibly previous JSON error  
  echo $e->getMessage(); // "Access token missing" (or sort of)
}
catch (AuthApiExceptionInterface $e) {
	echo $e->getMessage();
}

AuthToken

AuthTokenAuthTokenInterface依赖于德国的germania-kg/token软件包:https://packagist.org.cn/packages/germania-kg/token

接口 AuthTokenInterface

Germania\AuthApiClient\AuthTokenInterface 扩展了 Germania\Token\TokenInterface,因此提供了从 AuthTokenInterface 继承的这些方法:

interface AuthTokenInterface
{
    // Alias for "getContent"
    public function __toString();

    // Returns the token "text".
  	public function getContent() : string;

    // Returns the lifetime in seconds.
    public function getLifeTime() : int;
}

类 AuthToken

Germania\AuthApiClient\AuthToken 实现了 AuthTokenInterface。它是从 Germania\Token\Token 扩展而来的。

<?php
use Germania\AuthApiClient\AuthToken;

// Pass token string and TTL
$auth_token = new AuthToken( "somerandomstring", 3600);

// Inherited from "Token" class
echo $auth_token;                // "somerandomstring"
echo $auth_token->__toString();  // "somerandomstring"  
echo $auth_token->getContent();  // "somerandomstring"  
echo $auth_token->getLifeTime(); // 3600

创建授权请求:PSR-17 请求工厂

一旦你有了你的 AuthToken,你将想要在 API 中进行授权。为了创建一个授权的 PSR-7 请求,你可以使用类 AuthTokenRequestFactory,该类包装了另一个“内部”PSR-17 RequestFactory。

构造函数需要一个 AuthToken 实例或等效的 string;它可以选择接受任何 PSR-17 实例;默认情况下,将使用 Nyholm 的 PSR-17 RequestFactory

<?php
use Germania\AuthApiClient\AuthTokenRequestFactory;

# Have your AuthToken and, optionally, another PSR-17 Request Factory at hand:
$auth_token = ...
$inner_request_factory = new \Nyholm\Psr7\Factory\Psr17Factory;

$psr17 = AuthTokenRequestFactory( $auth_token );
$psr17 = AuthTokenRequestFactory( $auth_token ), $inner_request_factory);

$request = $psr17->createRequest("GET", "/");
// true
$request->hasHeader("Authorization");

测试

phpunit.xml.dist 复制到 phpunit.xml,并在 <php> 部分填写你的凭证。

$ composer phpunit