nickveenhof/http-hmac-php

PHP 中 HTTP HMAC 规范的实现,与 Symfony 和 Guzzle 等流行库集成。使用不同的命名空间以避免与内容中心的版本冲突。临时!

3.1.3 2016-09-05 13:11 UTC

README

Build Status Code Coverage HHVM Status Scrutinizer Code Quality Total Downloads Latest Stable Version License

HMAC 请求签名器是一个 PHP 库,实现了 HTTP HMAC 规范 的 2.0 版本,用于对 RESTful Web API 请求进行签名和验证。它集成了 Symfony 和 Guzzle 等流行库,可以在服务器和客户端上使用。

安装

可以通过将 HMAC 请求签名器添加为依赖项到项目的 composer.json 文件,使用 Composer 进行安装。

{
    "require": {
        "nickveenhof/http-hmac-php": "~3.1.0"
    }
}

有关更详细安装和用法说明,请参阅 Composer 的文档

用法

使用 Guzzle 发送 API 请求进行签名

use NickVeenhof\Hmac\Guzzle\HmacAuthMiddleware;
use NickVeenhof\Hmac\Key;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// Optionally, you can provide signed headers to generate the digest. The header keys need to be provided to the middleware below.
$options = [
  'headers' => [
    'X-Custom-1' => 'value1',
    'X-Custom-2' => 'value2',
  ],
];

// A key consists of your UUID and a MIME base64 encoded shared secret.
$key = new Key('e7fe97fa-a0c8-4a42-ab8e-2c26d52df059', base64_encode('secret'));

// Provide your key, realm and optional signed headers.
$middleware = new HmacAuthMiddleware($key, 'CIStore', array_keys($options['headers']));

// Register the middleware.
$stack = HandlerStack::create();
$stack->push($middleware);

// Create a client.
$client = new Client([
    'handler' => $stack,
]);

// Request.
$result = $client->get('https://service.acquia.io/api/v1/widget', $options);
var_dump($result);

使用 PSR-7 兼容的请求进行请求认证

use NickVeenhof\Hmac\RequestAuthenticator;
use NickVeenhof\Hmac\ResponseSigner;

// $keyLoader implements \NickVeenhof\Hmac\KeyLoaderInterface
$authenticator = new RequestAuthenticator($keyLoader);

// $request implements PSR-7's \Psr\Http\Message\RequestInterface
// An exception will be thrown if it cannot authenticate.
$key = $authenticator->authenticate($request);

$signer = new ResponseSigner($key, $request)
$signedResponse = $signer->signResponse($response);

使用 Silex 的 SecurityServiceProvider 进行认证

为了使用提供的 Silex 安全提供程序,您需要将以下可选库包含在项目的 composer.json

{
    "require": {
        "symfony/psr-http-message-bridge": "~0.1",
        "symfony/security": "~3.0",
        "zendframework/zend-diactoros": "~1.3.5"
    }
}

示例实现

use NickVeenhof\Hmac\HmacSecurityProvider;
use Silex\Application;
use Silex\Provider\SecurityServiceProvider;

$app = new Application();

// $keyLoader implements \NickVeenhof\Hmac\KeyLoaderInterface
$app->register(new SecurityServiceProvider());
$app->register(new HmacSecurityProvider($keyLoader));

$app['security.firewalls'] = [
    'hmac-auth' => array(
        'pattern' => '^/api/',
        'hmac' => true,
    ),
];

$app->boot();

使用 Symfony 的安全组件进行认证

为了使用提供的 Symfony 集成,您需要将以下可选库包含在项目的 composer.json

{
    "require": {
        "symfony/psr-http-message-bridge": "~0.1",
        "symfony/security": "~3.0",
        "zendframework/zend-diactoros": "~1.3.5"
    }
}

示例实现

# app/config/services.yml
services:
    hmac.security.authentication.provider:
        class: NickVeenhof\Hmac\Symfony\HmacAuthenticationProvider
        arguments:
            - '@hmac.request.authenticator' # Service should implement \NickVeenhof\Hmac\RequstAuthenticatorInterface
        public: false

    hmac.security.authentication.listener:
        class: NickVeenhof\Hmac\Symfony\HmacAuthenticationListener
        arguments: ['@security.token_storage', '@security.authentication.manager']
        public: false

# app/config/security.yml
security:
    # ...

    firewalls:
        hmac_auth:
            pattern:   ^/api/
            stateless: true
            wsse:      true
// src/AppBundle/AppBundle.php
namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        // $hmacFactory should implement \Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface
        // @see https://symfony.ac.cn/doc/current/cookbook/security/custom_authentication_provider.html#the-factory
        $extension = $container->getExtension('security');
        $extension->addSecurityListenerFactory($hmacFactory);
    }
}

贡献和开发

使用 GitHub 的标准 pull request 工作流程提交更改。

所有代码都应遵守以下标准

使用 PHP_CodeSniffer 验证编码风格并根据 PSR-2 标准自动修复问题

$ vendor/bin/phpcs --standard=PSR2 --runtime-set ignore_warnings_on_exit true --colors src/.
$ vendor/bin/phpcs --standard=PSR2 --runtime-set ignore_warnings_on_exit true --colors test/.
$ vendor/bin/phpcbf --standard=PSR2 src/.
$ vendor/bin/phpcbf --standard=PSR2 test/.

有关此项目支持的 Apache Ant 目标,请参阅 PHP Project Starter 的文档