DEV Community

Rami Beshry
Rami Beshry

Posted on

Request-Bound HMAC Authentication in Laravel with MKAP

Why bind a proof to a request?

A static bearer token is easy to copy: once captured, the same value can often be replayed against a different request. MKAP takes a different approach. The server issues a short-lived challenge containing selected key identifiers. The client retrieves the corresponding secrets from its local pool and derives a proof bound to the HTTP method, the origin-form request target and the exact body bytes.

The protocol is framework-independent; the two Laravel packages are thin adapters around it. This article explains what each adapter actually does, what its configuration keys mean, and which parts of a working integration you still have to build yourself.

What the two packages are responsible for

proit365/laravel-multikey-auth-server is the server adapter. It provides an opt-in challenge route, request-authentication middleware, database-backed repositories bound in the container, a Laravel cache-backed rate limiter, and guarded Artisan commands for pools, keys, exports and challenge pruning.

proit365/laravel-multikey-auth is the client adapter. It wraps the PHP MKAP client with Laravel configuration, a Laravel HTTP transport, dependency injection and the MKAP facade. It authenticates outbound requests; it does not protect incoming application routes.

The server adapter does not globally secure your application. Only the challenge endpoint is registered, and only when explicitly enabled, and you must attach the middleware to the routes that need it.

Requirements and versions

Both packages require PHP ^8.2 and Laravel ^12.0 (the required illuminate/* components are constrained to ^12.0).

The server package additionally requires ext-pdo and a configured PDO driver, plus the framework-independent proit365/multikey-auth-server:^1.0; the client requires proit365/multikey-auth:^1.0.

The server README states that Laravel 13 is not supported by this package version; no other Laravel version is claimed here.

At the time of writing, Packagist lists v1.0.3 as the latest server release and v1.0.2 as the latest client release, both published on 2026-11-26.

Development dependencies are orchestra/testbench:^10.0 and phpunit/phpunit:^11.5 in both packages.

Installation commands

Server, in a Laravel 12 application:

composer require proit365/laravel-multikey-auth-server:^1.0
php artisan vendor:publish --tag=mkap-config
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Client:

composer require proit365/laravel-multikey-auth:^1.0
php artisan vendor:publish --tag=mkap-client-config
Enter fullscreen mode Exit fullscreen mode

Laravel package discovery registers MultiKeyAuthServiceProvider for the server and MultiKeyAuthClientServiceProvider plus the MKAP alias for the client, so no manual provider registration is needed in a standard installation.

Server configuration keys

The published file is config/multikey-auth-server.php. Its shipped defaults, together with the server guide, define the following keys.

Key Default Purpose
database_connection null Laravel database connection used by the MKAP repositories (MKAP_DATABASE_CONNECTION)
master_key_provider null Application class implementing MasterKeyProviderInterface (MKAP_MASTER_KEY_PROVIDER)
client_pool_provider null Optional custom ClientPoolProviderInterface
challenge_lifetime_seconds 30 Challenge lifetime; the guide gives a valid range of 1–3,600 seconds
maximum_challenge_body_bytes 65536 Maximum challenge request body
maximum_authenticated_body_bytes 1048576 Maximum protected API body
rate_limits.challenge 60 Challenge requests per decay interval and client
rate_limits.authenticate 120 Authenticated requests per decay interval and client
rate_limits.decay_seconds 60 Rate-limit interval in seconds
routes.enabled false Whether the package's challenge route is registered
routes.challenge_path v1/auth/challenges Challenge route path
routes.middleware ['api'] Middleware applied to that route

The master-key provider must be supplied by the application: it has to implement ProIT365\\MultiKeyAuth\\Core\\Server\\MasterKeyProviderInterface and return a versioned, 32-byte master key from an external secret manager. The package does not create, store or default a master key.

The default client-pool provider reads the package's database tables; a client must resolve to exactly one active pool. Custom lookup policies require a ClientPoolProviderInterface implementation.

What happens on an authenticated request

The challenge endpoint accepts JSON containing version, client_id, method, target and body_sha256, where body_sha256 is the unpadded base64url encoding of the SHA-256 hash of the exact API body.

A successful response includes version, request_id, nonce, key_ids, key_count, id_length, expires_in and expires_at, and is marked Cache-Control: no-store.

The middleware reads X-MKAP-Version, X-MKAP-Client, X-MKAP-Request and X-MKAP-Proof. It requires version 1, decodes the request identifier as 16 bytes and the proof as 32 bytes with strict canonical base64url checking, then calls the verifier with the uppercased HTTP method, getRequestUri(), the raw request body and protocol version 1. The next middleware or controller runs only after verification succeeds.

The server guide documents these error mappings for the current Laravel adapter: 400 for malformed JSON or invalid challenge metadata, 401 for missing, invalid, expired or mismatched proofs, 403 for an unknown client, 404 for an unknown challenge, 409 for replay, 413 for oversized requests, 429 for rate limits, and 500 for unexpected failures. These mappings describe this adapter's behavior, not universal Laravel behavior. The adapter does not currently emit 422.

Challenge route URL

When routes.enabled is true, the service provider loads routes/api.php and registers the configured routes.challenge_path with routes.middleware. The shipped path is /v1/auth/challenges and the shipped middleware is the api middleware group. Do not assume that the effective URL automatically contains an /api prefix. Laravel route and host configuration determine the final URL; verify it after enabling the endpoint:

php artisan route:list
Enter fullscreen mode Exit fullscreen mode

Protecting application routes

The service provider registers the multikey.auth middleware alias. Attach it only to routes that require MKAP.

use App\\Http\\Controllers\\OrderController;
use Illuminate\\Support\\Facades\\Route;

Route::middleware('multikey.auth')->group(function (): void {
    Route::post('/api/orders', [OrderController::class, 'store']);
});
Enter fullscreen mode Exit fullscreen mode

The middleware itself uses the uppercased HTTP method, getRequestUri(), getContent() and protocol version 1; it does not inspect proxy headers or apply a proxy-specific target policy. It is therefore the application's responsibility to ensure that TLS termination, proxy headers and upstream middleware preserve the method, request target and raw body before multikey.auth runs. Confirm this behavior in the target deployment rather than assuming it.

Calling an MKAP-protected API from Laravel

Configure the client through environment variables; the published config file supplies the defaults shown here.

MKAP_BASE_URI=https://api.example.test
MKAP_CLIENT_ID=CLIENT_001
MKAP_POOL_VERSION=1
MKAP_IDENTIFIER_LENGTH=6
MKAP_IDENTIFIER_ALPHABET=abcdefghijklmnopqrstuvwxyz0123456789
MKAP_EXPORT_PATH=/secure/application-data/mkap/client-export.json
MKAP_REQUIRE_HTTPS=true
Enter fullscreen mode Exit fullscreen mode

Serialize the body once and pass those exact bytes to the facade.

use ProIT365\\MultiKeyAuth\\LaravelClient\\Facades\\MKAP;

$body = json_encode(['status' => 'pending'], JSON_THROW_ON_ERROR);
$response = MKAP::post('/api/orders', $body);

if ($response->statusCode !== 201) {
    throw new RuntimeException('Order request did not succeed.');
}
Enter fullscreen mode Exit fullscreen mode

The same client is available by dependency injection.

use ProIT365\\MultiKeyAuth\\Client\\HttpResponse;
use ProIT365\\MultiKeyAuth\\LaravelClient\\LaravelMultiKeyClient;

final class OrderGateway
{
    public function __construct(
        private readonly LaravelMultiKeyClient $client
    ) {
    }

    public function submit(string $body): HttpResponse
    {
        return $this->client->post('/api/orders', $body);
    }
}
Enter fullscreen mode Exit fullscreen mode

HttpResponse exposes statusCode, headers and body, and non-2xx API responses are returned rather than thrown as transport exceptions. An API 401 is returned unchanged and is not retried. The facade supports request, get, post, put, patch and delete, and all targets must be origin-form paths that match what the server authenticates.

The README shows the same facade pattern with a 200 status check; that number is application-specific. The parts to preserve are single serialization, unchanged bytes, and no redirects or rewriting after signing.

Key and export administration

The server guide documents these Artisan commands.

Command Purpose
mkap:pools:generate <client_id> <pool_id> [--count=1000] [--selection=3] [--pool-version=1] [--identifier-length=6] [--alphabet=...] [--force] Create a pool and encrypted random keys
mkap:pools:inspect <pool_id> Show pool metadata and active/revoked key counts
mkap:keys:revoke <pool_id> <identifier> [--force] Revoke an active key
mkap:keys:rotate <pool_id> <identifier> [--reason=...] [--force] Revoke a key and create its replacement
mkap:exports:create <pool_id> [--client=...] --output=<path> [--development-json] [--force] Write a client export to a file
mkap:challenges:prune [--dry-run] Remove expired challenges without a retained audit record

There is no client-creation Artisan command in the Laravel package: create the client through the separate CLI package or your own administrative workflow before generating a pool.

The PHP client loads plaintext JSON through ExportLoader::fromJson(). Protected export envelopes are not supported by that loader. The server command currently exposes only the development JSON export mode. Treat that export as a credential, not as a production credential-delivery mechanism. A complete compromise of the export can allow an attacker to impersonate the client.

--force skips interactive confirmation but does not skip validation. Revocation and rotation take effect immediately; after rotation, issue a fresh export before clients use the replacement key.

What you must check before using any of this

The examples follow the API shapes documented in the packages' README and guide. None of it is a drop-in production setup. Before adopting it, check the following against your own application and the exact installed version:

  • Implement and configure a master-key provider backed by your external secret manager; the package intentionally supplies none.
  • Create the client record, generate a pool, produce an export and place it outside the public web root with restricted permissions; never commit it to source control or write it to logs.
  • Confirm that no middleware rewrites the method, request target or raw body before multikey.auth runs, and that proxies and TLS termination preserve them.
  • Configure a shared cache store if you run multiple workers or servers; the package uses Laravel's cache limiter, and a process-local cache does not provide shared enforcement.
  • Enforce request-size limits at the web server/PHP layers in addition to maximum_challenge_body_bytes and maximum_authenticated_body_bytes, and keep HTTPS enabled.
  • Match pool_version, identifier_length and identifier_alphabet to the export metadata; a stale export cannot prove possession of a newly selected key.
  • Re-run the installed package's own tests (composer install then composer test) and test the complete network path in the target environment; package tests do not verify production HTTPS, shared cache configuration or multi-worker deployment.
  • Re-check the version constraints and release notes on Packagist at the time of adoption, since this article reflects only the versions listed above.

Deployment limitations

The internal architecture note describes a local deployment demonstration: a single-host Docker Compose stack with Caddy TLS on loopback ports, an nginx reverse proxy to PHP-FPM, MySQL and Redis, a one-shot bootstrap, a shared read-only client export volume and a two-replica application overlay. It uses a local self-signed CA and file-based demo secrets.

That demonstration is not a public production deployment and should not be described as one. The package tests and local demonstration do not verify public TLS, target-environment request-limit behavior, proxy preservation of signed fields, distributed replay protection, concurrent challenge consumption or production deployment readiness. None of this should be turned into a production-readiness, security-certification or customer-adoption claim.

Limitations and disclosure

MKAP is a custom authentication protocol under development. It is not currently recommended for production use, has not undergone an independent cryptographic security review, and must not be considered production-secure or independently audited.

Published-package and loopback integration tests are evidence of tested behavior only, not production certification. Protected-export envelopes are not supported by the currently released PHP/Laravel client loader. Distributed replay protection, shared rate limiting and concurrent challenge consumption remain unverified; target-environment deployment checks and independent security review remain outstanding.

This is a community-oriented technical article, not an announcement of a production release, adoption, traffic or customer results. No votes, likes, reviews or purchases are requested.

The author is a maintainer of the MKAP project.

Project links

Sources

  1. Server package on Packagist
  2. Server README — v1.0.3 source commit
  3. Server composer.json — v1.0.3 source commit
  4. Server configuration — v1.0.3 source commit
  5. Server middleware — v1.0.3 source commit
  6. Server service provider — v1.0.3 source commit
  7. Server guide — v1.0.3 source commit
  8. Client package on Packagist
  9. Client README — v1.0.2 source commit
  10. Client composer.json — v1.0.2 source commit
  11. Client configuration — v1.0.2 source commit
  12. Client guide — v1.0.2 source commit
  13. MKAP monorepo README
  14. MKAP security policy
  15. MKAP known limitations``

Top comments (0)