kaxiluo / api-signature
API 签名和验证,Guzzle 签名中间件,签名验证中间件
1.1.0
2021-05-29 15:54 UTC
Requires
- php: >=7.0
- ext-json: *
- guzzlehttp/guzzle: ~6.0|~7.0
- nyholm/psr7: ^1.4
- psr/http-message: ^1.0
- psr/http-server-middleware: ^1.0
- psr/simple-cache: ^1.0
- symfony/psr-http-message-bridge: ^2.1
Requires (Dev)
- mockery/mockery: 1.3.2
- phpunit/phpunit: ~7.0
This package is auto-updated.
Last update: 2024-09-29 06:20:16 UTC
README
API 签名和验证,易于通过中间件使用。或者独立使用。
- 请求签名者
- 使用请求签名中间件创建 Guzzle 客户端
- 签名验证器
- 通用签名验证中间件
- 在 Laravel、Hyperf 等中使用签名验证中间件
安装
该包可在 Packagist 上找到,
composer require kaxiluo/api-signature
使用方法
客户端(请求签名)
// use as guzzle client config $config = [ 'base_uri' => 'https://yourserver.host', 'verify' => false, ]; // create guzzle client with request sign middleware $client = \Kaxiluo\ApiSignature\Client\GuzzleClientFactory::createClient('1', 'iamsecret', $config); // enjoy.. $client->get('/test');
其他,独立使用请参阅:\Kaxiluo\ApiSignature\Client\RequestSigner
服务器(签名验证)
使用 Laravel 中间件
use Kaxiluo\ApiSignature\Server\SignatureVerifyLaravelMiddleware; class MySignatureVerifyMiddleware extends SignatureVerifyLaravelMiddleware { // custom signature header name. default is X-Signature protected $headerName = 'X-Your-Custom-Name'; // nonce ttl. default is 300 s protected $lifetime = 500; protected function getAppSecretByAppId($appId): string { // TODO: Implement getAppSecretByAppId() method. // you can filter app_secret from config //return config('api.your-client.app_secret'); } protected function getCacheProvider() { return app('cache.store'); } }
使用 Hyperf 中间件
use Kaxiluo\ApiSignature\Exception\InvalidSignatureException; use Kaxiluo\ApiSignature\Server\SignatureVerifyPsrMiddleware; use Psr\Container\ContainerInterface; use Psr\SimpleCache\CacheInterface; class MySignatureVerifyMiddleware extends SignatureVerifyPsrMiddleware { /** * @var ContainerInterface */ protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } protected function handleInvalidSignature(InvalidSignatureException $exception) { return $this->container->get(\Hyperf\HttpServer\Contract\ResponseInterface::class) ->json(['error' => $exception->getMessage()]) ->withStatus(401); } protected function getCacheProvider(): CacheInterface { return $this->container->get(CacheInterface::class); } protected function getAppSecretByAppId($appId): string { // TODO: Implement getAppSecretByAppId() method. // you can filter app_secret from config } }
其他,独立使用请参阅:\Kaxiluo\ApiSignature\Server\SignatureValidator,\Kaxiluo\ApiSignature\Server\SignatureVerifyMiddleware