Created
April 7, 2017 05:43
-
-
Save paulredmond/8a974779d11d6e9950be2d73805e8115 to your computer and use it in GitHub Desktop.
Example Guzzle HTTP Middleware for a simple HMAC Authorization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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