PHP code example of macgirvin / http-message-signer
1. Go to this page and download the library: Download macgirvin/http-message-signer library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
macgirvin / http-message-signer example snippets
use GuzzleHttp\Psr7\ServerRequest;
$request = ServerRequest::fromGlobals();
use GuzzleHttp\Psr7\Request;
// Generate PSR7 request from current HTTP request, which is NOT
// affected by the use of Apache mod-rewrite or equivalent.
function createRequest(string $baseurl)
{
/**
* $baseurl for your site e.g. 'https://example.com'
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$input = file_get_contents('php://input');
}
$headers = [];
if (isset($_SERVER['CONTENT_TYPE'])) {
$headers['content-type'] = $_SERVER['CONTENT_TYPE'];
}
if (isset($_SERVER['CONTENT_LENGTH'])) {
$headers['content-length'] = $_SERVER['CONTENT_LENGTH'];
}
foreach ($_SERVER as $k => $v) {
if (str_starts_with($k, 'HTTP_')) {
$field = str_replace('_', '-', strtolower(substr($k, 5)));
$headers[$field] = $v;
}
}
return new Request(
$_SERVER['REQUEST_METHOD'],
$baseurl . $_SERVER['REQUEST_URI']),
$headers,
$input ?? null
);
}
use HttpSignature\HttpMessageSigner;
use HttpSignature\UnProcessableSignatureException;
use GuzzleHttp\Psr7\Request;
$request = new Request(
'GET',
'https://api.example.com/resource?bat&baz=3',
[
'Host' => 'api.example.com',
'Date' => gmdate('D, d M Y H:i:s T'),
...additional headers
]
);
$signer = (new HttpMessageSigner())
->setPrivateKey($privateKey) // only needed for signing
->setPublicKey($publicKey) // only needed for verifying
->setKeyId('https://example.com/dave#rsaKey') //
catch (UnProcessableSignatureException $exception) {
$whatHappened = $exception->getMessage();
}
try {
$isValid = $signer->verifyRequest($request);
} catch (UnProcessableSignatureException $exception) {
$isValid = false;
$whatHappened = $exception->getMessage();
}