Skip to content

Instantly share code, notes, and snippets.

@paulredmond
Created April 7, 2017 05:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulredmond/8a974779d11d6e9950be2d73805e8115 to your computer and use it in GitHub Desktop.
Save paulredmond/8a974779d11d6e9950be2d73805e8115 to your computer and use it in GitHub Desktop.
Example Guzzle HTTP Middleware for a simple HMAC Authorization
<?php
namespace App;
use Carbon\Carbon;
use Psr\Http\Message\RequestInterface;
class HMACRequestHandler
{
private $key;
private $secret;
public function __construct($key, $secret)
{
$this->key = $key;
$this->secret = $secret;
}
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options) use ($handler) {
$dateStr = Carbon::now()->format('D, d M Y H:i:s e');
$signature = $this->generateSignature(sprintf("date: %s", $dateStr));
$request = $request->withAddedHeader('Date', $dateStr);
$headerValue = 'Signature keyId="%s",algorithm="hmac-sha1",signature="%s"';
$request = $request->withAddedHeader(
'Authorization',
sprintf($headerValue, $this->key, $signature)
);
return $handler($request, $options);
};
}
private function generateSignature($payload)
{
$signature = hash_hmac("sha1", $payload, $this->secret, true);
$signature = base64_encode($signature);
$signature = rawurlencode($signature);
return $signature;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment