uma/psr7-hmac

An HMAC authentication library built on top of the PSR-7 specification

v1.0.0 2020-12-26 03:06 UTC

This package is auto-updated.

Last update: 2024-11-27 00:20:55 UTC


README

An HMAC authentication library built on top of the PSR-7 specification.

.github/workflows/phpunit.yml Code Coverage Scrutinizer Code Quality Total Downloads

Releases

Latest Stable Version

If you want to build an HMAC-authenticated API based on Symfony check out UMAPsr7HmacBundle, which provides a convenient integration of this library with Symfony's Security Component.

Library API

/**
 * @param string $secret
 */
Signer::__construct($secret);

/**
 * @param RequestInterface $request
 *
 * @return RequestInterface
 */
Signer::sign(RequestInterface $request);

/**
 * @param InspectorInterface|null $inspector
 */
Verifier::__construct(InspectorInterface $inspector = null);

/**
 * @param RequestInterface $request
 * @param string           $secret
 *
 * @return bool
 */
Verifier::verify(RequestInterface $request, $secret);

Demo Script

<?php

require_once __DIR__.'/vendor/autoload.php';

use UMA\Psr7Hmac\Signer;
use UMA\Psr7Hmac\Verifier;


//// CLIENT SIDE
$psr7request = new \Zend\Diactoros\Request('http://www.example.com/index.html', 'GET');
// GET /index.html HTTP/1.1
// host: www.example.com

$signer = new Signer('secret');

$signedRequest = $signer->sign($psr7request);
// GET /index.html HTTP/1.1
// host: www.example.com
// authorization: HMAC-SHA256 63IQ8RWDbC9p4ipNrkJz0e0UeGiBrR96zkNdujE5cl8=
// signed-headers: host,signed-headers


//// SERVER SIDE
$verifier = new Verifier();

var_dump($verifier->verify($signedRequest, 'secret'));
// true

var_dump($verifier->verify($signedRequest, 'another secret'));
// false

// Headers added after calling sign() do not break the verification, as
// they are not included in the signed-headers list.
var_dump($verifier->verify($signedRequest->withHeader('User-Agent', 'PHP/5.x'), 'secret'));
// true

// Changes made to any chunk of data that was present at the time of the
// signature are still detected, though. In this example a signed header
// is omitted from the Signed-Headers list.
var_dump($verifier->verify($signedRequest->withHeader('Signed-Headers', 'host,signed-headers'), 'secret'));
// false

// The verification also fails if any single part of the request is
// removed altogether after signing it.
var_dump($verifier->verify($signedRequest->withoutHeader('Signed-Headers'), 'secret'));
// false

External Resources

Disclaimer

The code included in this library has not been reviewed by any cryptographer or security specialist, nor I claim to be one. If you intend to use in your own projects you are advised to read the documentation, understand the code and report back any issues you shall find.