mickaelbaudoin / simple-sign-request
签名请求 REST API
dev-master
2016-10-03 20:11 UTC
Requires
- php: >5.5
Requires (Dev)
- guzzlehttp/guzzle: 6.2.1
This package is auto-updated.
Last update: 2024-09-28 10:38:07 UTC
README
使用 hmac_sha256 编码的 base64 检查签名请求客户端
代码示例
服务器端
使用 zend-expressive
- 创建用于注入共享密钥的中间件工厂
<?php
namespace Foo;
use Interop\Container\ContainerInterface;
/**
* Description of SignatureRequestMiddlewareFactory
*/
class SignatureRequestMiddlewareFactory {
public function __invoke(ContainerInterface $container)
{
$middleware = new \MB\SignatureRequestMiddleware($secret);
$middleware->addIgnorePath('/auth');
return $middleware;
}
}
- SignatureRequestMiddleware 构造函数的可选参数
\MB\SignatureRequestMiddleware($secret,$headersCustom = array(), $expireSecond = 60);
- 编辑配置文件以配置 Factories 和 Middlewares
middleware-pipeline.global.php
<?php
use Zend\Expressive\Container\ApplicationFactory;
use Zend\Expressive\Helper;
return [
'dependencies' => [
'factories' => [
Helper\ServerUrlMiddleware::class => Helper\ServerUrlMiddlewareFactory::class,
Helper\UrlHelperMiddleware::class => Helper\UrlHelperMiddlewareFactory::class,
MB\SignatureRequestMiddleware::class => SignatureRequestMiddlewareFactory::class
],
],
// This can be used to seed pre- and/or post-routing middleware
'middleware_pipeline' => [
.
.
'routing' => [
'middleware' => [
ApplicationFactory::ROUTING_MIDDLEWARE,
Helper\UrlHelperMiddleware::class,
MB\SignatureRequestMiddleware::class,
// Add more middleware here that needs to introspect the routing
// results; this might include:
// - route-based authentication
// - route-based validation
// - etc.
ApplicationFactory::DISPATCH_MIDDLEWARE,
],
'priority' => 1,
],
.
.
.
客户端
PHP
$secret = 'secret';
$method = 'GET';
$timestamp = time();
$token = '123456789';
$once = '2536';
$uri = 'https:///article/12';
//headers required
$headers = [
'X-API-token' => $token,
'X-API-timestamp' => $timestamp,
'X-API-once' => $once
];
//headers custom (optional)
$headersCustom = [
'X-API-realm' => 'foo'
];
//Generated signature
$data = ($method . $timestamp . $token . $once . $uri);
if(count($headersCustom) > 0){
foreach($headersCustom as $value){
$data .= $value;
}
}
$hash = base64_encode(hash_hmac('sha256', $data, $secret,true));
$headers['X-API-signature'] = $hash;
//Sending request with curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$uri);
curl_setopt($ch, CURLOPT_GET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);