PHPackages                             rysonliu/http-signature - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. rysonliu/http-signature

ActiveLibrary[HTTP &amp; Networking](/categories/http)

rysonliu/http-signature
=======================

Implementation of the IETF HTTP Signatures draft RFC

v1.2.0(1y ago)0793↓50%MITPHPPHP &gt;=7.2.0

Since Jan 17Pushed 1y agoCompare

[ Source](https://github.com/rysonliu/http-signature)[ Packagist](https://packagist.org/packages/rysonliu/http-signature)[ RSS](/packages/rysonliu-http-signature/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (10)Versions (3)Used By (0)

HTTP Signature service and middleware (PHP)
===========================================

[](#http-signature-service-and-middleware-php)

[![Build Status](https://camo.githubusercontent.com/9fe6fa834e856f07c19ff783a685301ffd0e91726b9b928838f0036de96b0069/68747470733a2f2f7472617669732d63692e6f72672f6a61736e792f687474702d7369676e61747572652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jasny/http-signature)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/0cd7cdaf47be2c02d0cab05c8bb8509af070e95bb7d1c72c788650b3c731979e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f687474702d7369676e61747572652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/http-signature/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/05413a2f2a7416584fe7d7d886b3001199d706c62d64c746a9eac1fe5e337763/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f687474702d7369676e61747572652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/http-signature/?branch=master)[![Packagist Stable Version](https://camo.githubusercontent.com/de9cb7891a7f4490131e3b87c03c92b0ceba9a2fd6bb1d3c0942cb7269a39e27/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a61736e792f687474702d7369676e61747572652e737667)](https://packagist.org/packages/jasny/http-signature)[![Packagist License](https://camo.githubusercontent.com/4031332116c65debbc636324f40e46a6c00d5f080b38d987d9202b004f7b4b7e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a61736e792f687474702d7369676e61747572652e737667)](https://packagist.org/packages/jasny/http-signature)

This library provides a service for implementing the [IETF HTTP Signatures draft RFC](https://tools.ietf.org/html/draft-cavage-http-signatures). It includes PSR-7 compatible middleware for signing requests (by an HTTP client like Guzzle) and verifying http signatures.

Installation
------------

[](#installation)

```
composer require rysonliu/http-signature

```

Usage
-----

[](#usage)

When creating the `HttpSignature` service, pass a list of supported algorithms, a callback to sign request and a callback to verify signatures.

```
use Jasny\HttpSignature\HttpSignature;

$keys = [
  'hmac-key-1' => 'secret',
  'hmac-key-2' => 'god',
];

$service = new HttpSignature(
    'hmac-sha256',
    function (string $message, string $keyId) use ($keys): string {
        if (!isset($keys[$keyId])) {
            throw new OutOfBoundsException("Unknown sign key '$keyId'");
        }

        $key = $keys[$keyId];
        return hash_hmac('sha256', $message, $key, true);
    },
    function (string $message, string $signature, string $keyId) use ($keys): bool {
        if (!isset($keys[$keyId])) {
            return false;
        }

        $key = $keys[$keyId];
        $expected = hash_hmac('sha256', $message, $key, true);

        return hash_equals($expected, $signature);
    }
);
```

### Signing request

[](#signing-request)

You can use the service to sign a PSR-7 Request.

```
$request = new Request(); // Any PSR-7 compatible Request object
$signedRequest = $service->sign($request, $keyId);
```

### Verifying requests

[](#verifying-requests)

You can use the service to verify the signature of a signed a PSR-7 Request.

```
$request = new Request(); // Any PSR-7 compatible Request object
$service->verify($request);
```

If the request is not signed, the signature is invalid, or the request doesn't meet the requirements, an `HttpSignatureException` is thrown.

### Configuring the service

[](#configuring-the-service)

#### Multiple algorithms

[](#multiple-algorithms)

Rather than specifying a single algorithm, an array of supported algorithms may be specified in the constructor. The used algorithm is passed as extra parameter to the sign and verify callbacks.

```
use Jasny\HttpSignature\HttpSignature;

$service = new HttpSignature(
    ['hmac-sha256', 'rsa', 'rsa-sha256'],
    function (string $message, string $keyId, string $algorithm): string {
        // ...
    },
    function (string $message, string $signature, string $keyId, string $algorithm): bool {
        // ...
    }
);
```

When signing, specify the algorithm;

```
$signedRequest = $service->sign($request, $keyId, 'hmac-sha256');
```

Alternatively you can get a copy of the service with one of the algorithms selected.

```
$signService = $service->withAlgorithm('hmac-sha256');
$signService->sign($request, $keyId);
```

#### Required headers

[](#required-headers)

By default, the request target (includes the HTTP method, URL path and query parameters) and the `Date` header are required to be part of the signature message for all types of requests.

```
$service = $service->withRequiredHeaders('POST', ['(request-target)', 'date', 'content-type', 'digest']);
```

The required headers can be specified per request method or as `default`.

Note that the requirement only applies on including the headers to create the signature. If the headers are not used in the request, they are also not part of the signature. Checking if headers are set in the request and have a valid value, is outside the scope of this library.

#### Date header

[](#date-header)

If a `Date` header is specified, the service will check the age of the request. If it's signed to long ago an exception is thrown. By default a request may not be more than 300 seconds (5 minutes) old.

The time between signing a request and verifying it, may be due to latency or the system clock of client and/or server might be off.

The time that is allowed can be configured as clock skew;

```
$service = $service->withClockSkew(1800); // Accept requests up to 30 minutes old
```

**X-Date header**

Browsers automatically set the `Date` header for AJAX requests. This makes it impossible to use this for the signature. As solution, an `X-Date` header may be used that supersedes the `Date` header.

### Server middleware

[](#server-middleware)

Server middleware can be used to verify PSR-7 requests.

If the request is signed but the signature is invalid, the middleware will return a `401 Unauthorized` response and the handler will not be called.

#### Single pass middleware (PSR-15)

[](#single-pass-middleware-psr-15)

The middleware implements the PSR-15 `MiddlewareInterface`. As PSR standard many new libraries support this type of middleware, for example [Zend Stratigility](https://docs.zendframework.com/zend-stratigility/).

You're required to supply a [PSR-17 response factory](https://www.php-fig.org/psr/psr-17/#22-responsefactoryinterface), to create a `401 Unauthorized` response for requests with invalid signatures.

```
use Jasny\HttpSignature\HttpSignature;
use Jasny\HttpSignature\ServerMiddleware;
use Zend\Stratigility\MiddlewarePipe;
use Zend\Diactoros\ResponseFactory;

$service = new HttpSignature(/* ... */);
$responseFactory = new ResponseFactory();
$middleware = new ServerMiddleware($service, $responseFactory);

$app = new MiddlewarePipe();
$app->pipe($middleware);
```

#### Double pass middleware

[](#double-pass-middleware)

My PHP libraries support double pass middleware. These are callables with the following signature;

```
fn(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
```

To get a callback to be used by libraries as [Jasny Router](https://github.com/jasny/router) and [Relay](http://relayphp.com/), use the `asDoublePass()` method.

When using as double pass middleware, the supplying a resource factory is optional. If not supplied, it will use the response passed when invoked.

```
use Jasny\HttpSignature\HttpSignature;
use Jasny\HttpSignature\ServerMiddleware;
use Relay\RelayBuilder;

$service = new HttpSignature(/* ... */);
$middleware = new ServerMiddleware($service);

$relayBuilder = new RelayBuilder($resolver);
$relay = $relayBuilder->newInstance([
    $middleware->asDoublePass(),
]);

$response = $relay($request, $baseResponse);
```

#### Verifying requests

[](#verifying-requests-1)

If a request is signed and the signature is valid, the middle with set a `signature_key_id` request attribute.

For requests that are *not* signed, the middleware does nothing. This means that you need to always check if the request has the `signature_key_id`.

```
$keyId = $request->getAttribute(`signature_key_id`);

if ($keyId === null) {
    $errorResponse = $response
        ->withStatus(401)
        ->withHeader('Content-Type', 'text/plain');

    $errorResponse = $service->setAuthenticateResponseHeader($errorResponse);
    $errorResponse->getBody()->write('request not signed');
}

// Request is signed and signature is valid
// ...
```

### Client middleware

[](#client-middleware)

Client middleware can be used to sign requests send by PSR-7 compatible HTTP clients like [Guzzle](http://docs.guzzlephp.org) and [HTTPlug](http://docs.php-http.org).

```
use Jasny\HttpSignature\HttpSignature;
use Jasny\HttpSignature\ClientMiddleware;

$service = new HttpSignature(/* ... */);
$middleware = new ClientMiddleware($service, $keyId);
```

The `$keyId` is used to the `Authorization` header and passed to the sign callback.

If the service supports multiple algorithms you need to use the `withAlgorithm` method to select one.

```
$middleware = new ClientMiddleware($service->withAlgorithm('hmac-sha256'));
```

#### Double pass middleware

[](#double-pass-middleware-1)

The client middleware can be used by any client that does support double pass middleware. Such middleware are callables with the following signature;

```
fn(RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
```

Most HTTP clients do not support double pass middleware, but a type of single pass instead. However more general purpose PSR-7 middleware libraries, like [Relay](http://relayphp.com/), do support double pass.

```
use Relay\RelayBuilder;

$relayBuilder = new RelayBuilder($resolver);
$relay = $relayBuilder->newInstance([
    $middleware->asDoublePass(),
]);

$response = $relay($request, $baseResponse);
```

*The client middleware does not conform to PSR-15 (single pass) as that is intended for server requests only.*

#### Guzzle

[](#guzzle)

[Guzzle](http://docs.guzzlephp.org) is the most popular HTTP Client for PHP. The middleware has a `forGuzzle()` method that creates a callback which can be used as Guzzle middleware.

When using the middleware for Guzzle, it's not required to pass a `$keyId` to the constructor. Instead use Guzzle option `signature_key_id`. This also allows the option use different keys per request or disable signing for requests.

```
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Client;
use Jasny\HttpSignature\HttpSignature;
use Jasny\HttpSignature\ClientMiddleware;

$service = new HttpSignature(/* ... */);
$middleware = new ClientMiddleware($service);

$stack = new HandlerStack();
$stack->push($middleware->forGuzzle());

$client = new Client(['handler' => $stack, 'signature_key_id' => $keyId]);

$client->get('/foo');                                    // Sign with default key
$client->get('/foo', ['signature_key_id' => $altKeyId]); // Sign with other key
$client->get('/foo', ['signature_key_id' => null]);      // Don't sign
```

Alternatively, you can disable signing by default and only sign when specified;

```
$client = new Client(['handler' => $stack]);

$client->get('/foo');                                 // Don't sign
$client->get('/foo', ['signature_key_id' => $keyId]); // Sign
```

*Using an option is only available for Guzzle. For HTTPlug and other clients, you need to create a client per key or sign without the use of middleware.*

#### HTTPlug

[](#httplug)

[HTTPlug](http://docs.php-http.org/en/latest/httplug/introduction.html) is the HTTP client of PHP-HTTP. It allows you to write reusable libraries and applications that need an HTTP client without binding to a specific implementation.

The `forHttplug()` method for the middleware creates an object that can be used as HTTPlug plugin.

```
use Http\Discovery\HttpClientDiscovery;
use Http\Client\Common\PluginClient;
use Jasny\HttpSignature\HttpSignature;
use Jasny\HttpSignature\ClientMiddleware;

$service = new HttpSignature(/* ... */);
$middleware = new ClientMiddleware($service, $keyId);

$pluginClient = new PluginClient(
    HttpClientDiscovery::find(),
    [
        $middleware->forHttplug(),
    ]
);
```

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance48

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 86.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~428 days

Total

2

Last Release

415d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/783fdbc932bfd33d87589e1283ee211a362458c8077c81a7e03f6d606733f0f1?d=identicon)[rysonlau](/maintainers/rysonlau)

---

Top Contributors

[![jasny](https://avatars.githubusercontent.com/u/100821?v=4)](https://github.com/jasny "jasny (32 commits)")[![rysonliu](https://avatars.githubusercontent.com/u/55525541?v=4)](https://github.com/rysonliu "rysonliu (3 commits)")[![Minstel](https://avatars.githubusercontent.com/u/6154708?v=4)](https://github.com/Minstel "Minstel (1 commits)")[![svenstm](https://avatars.githubusercontent.com/u/1632578?v=4)](https://github.com/svenstm "svenstm (1 commits)")

### Embed Badge

![Health badge](/badges/rysonliu-http-signature/health.svg)

```
[![Health](https://phpackages.com/badges/rysonliu-http-signature/health.svg)](https://phpackages.com/packages/rysonliu-http-signature)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[neos/flow

Flow Application Framework

862.0M449](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
