Search by

oihana / php-m2m

ooop

Lightweight, OIDC-compliant Machine-to-Machine (M2M) HTTP client for APIs protected by JWT — implements the OAuth 2.0 jwt-bearer flow (RFC 7521 + RFC 7523).

2.1.0 2026-11-26 16:41 UTC

This package is auto-updated.

Last update: 2026-11-26 16:42:19 UTC


README

Oihana PHP M2M

Lightweight, OIDC-compliant Machine-to-Machine (M2M) HTTP client for APIs protected by JWT.

Implements the OAuth 2.0 JWT bearer authorization grant (urn:ietf:params:oauth:grant-type:jwt-bearer, RFC 7521 + RFC 7523) so a service account can sign a short-lived JWT assertion with its own RSA key, exchange it at the identity provider's token endpoint for an access token, and call a protected API with Authorization: Bearer ….

Designed for Zitadel out of the box, compatible with any RFC 7523-compliant identity provider (Auth0, Keycloak, …) via a configurable token endpoint path.

Latest Version Total Downloads License

✨ Features

  • Two-line setup from a self-sufficient keyfile JSON — no global config, no service container required.
  • Proactive token caching — one IdP exchange per ~59 minutes (REFRESH_SAFETY_MARGIN).
  • Optional shared cache (PSR-16) — the processes of a web application (PHP-FPM) share one token instead of performing one exchange per request ; a failing cache never fails a call.
  • Reactive 401 retry — handles clock drift and premature revocation with one transparent re-exchange, and never retries a 401 that a fresh token cannot fix.
  • Strongly typed errors — every non-2xx answer raises an ApiResponseException carrying its status, reason and Retry-After ; a dead keyfile (KeyfileInvalidException) is told apart from an identity provider that is down (IdentityProviderUnavailableException).
  • Secure by default — https:// required, the Bearer never leaves the API host, the token endpoint follows no redirection, and the private key never shows in a var_dump() or a stack trace.
  • Few dependencies — firebase/php-jwt and guzzlehttp/guzzle, both majors of each supported, plus the PSR-16 interfaces (psr/simple-cache).
  • IdP-agnostic — defaults to Zitadel's /oauth/v2/token, override $tokenPath for Auth0, Keycloak, …
  • Subclass-friendly — call(), doRequest(), decodeResponse() are protected extension hooks for instrumentation, correlation IDs, custom envelopes.
  • Zero hidden state — pass your own Guzzle client to inject middlewares (logging, retry-on-5xx, telemetry).

📦 Installation

Requires PHP 8.4+ with ext-json and ext-openssl.

Install via Composer:

composer require oihana/php-m2m:^2.0

Upgrading from 1.x ? See documentation/en/upgrading.md.

🚀 Quick Start

1. Obtain a keyfile

A keyfile is a JSON document handed to you once by the API administrator at service creation (or key rotation). It is never persisted server-side — store it securely on the calling service's host (file system, secret manager, …).

A keyfile is auto-sufficient: it carries both the cryptographic material (the RSA private key + key id) and the connection metadata (issuer URL, API base URL, OAuth2 scope) so a third-party developer can connect without any further configuration.

{
    "type":        "serviceaccount",
    "keyId":       "303384786189271040",
    "key":         "-----BEGIN RSA PRIVATE KEY-----\n…\n-----END RSA PRIVATE KEY-----\n",
    "userId":      "303384547813785600",
    "issuer":      "https://my-org.zitadel.cloud",
    "audience":    "303380000000000000",
    "scope":       "openid profile urn:zitadel:iam:org:project:id:303380000000000000:aud",
    "apiBaseUrl":  "https://api.example.com"
}

See documentation/en/keyfile-format.md for the full field reference.

2. Call the API

use oihana\m2m\M2MApiClient;

$client = M2MApiClient::fromKeyfile( '/secrets/m2m-keyfile.json' ) ;

$widgets = $client->get   ( '/widgets' ) ;
$created = $client->post  ( '/widgets'      , [ 'name' => 'Foo' ] ) ;
$updated = $client->patch ( '/widgets/42'   , [ 'name' => 'Bar' ] ) ;
$client->delete( '/widgets/42' ) ;

That's it. Token acquisition, caching, refresh, and 401 retry are handled internally.

3. Override fields when needed

A typical use case is pointing a staging keyfile at a local API for end-to-end testing:

$client = M2MApiClient::fromKeyfile
(
    keyfilePath   : '/secrets/staging-keyfile.json' ,
    apiBaseUrl    : 'http://localhost:8000' ,        // override apiBaseUrl
    allowInsecure : true                             // http:// for a local test only — never in production
) ;

Same for $issuer, $scope, $tokenPath, and the underlying Guzzle $http client. Without allowInsecure, an http:// URL is refused.

🌐 Identity provider compatibility

The token endpoint path defaults to /oauth/v2/token (Zitadel convention). Override it for other providers:

Identity provider $tokenPath
Zitadel (default) /oauth/v2/token
Auth0 /oauth/token
Keycloak /realms/{realm}/protocol/openid-connect/token
Generic RFC 7523 whatever your IdP exposes
$client = new M2MApiClient
(
    keyfile   : $keyfile ,
    tokenPath : '/oauth/token'  // Auth0
) ;

🔁 Token lifecycle

  • Proactive refresh — the access token is cached in memory with its expires_in and reused for every call until 60 seconds before its expiration (REFRESH_SAFETY_MARGIN). No exchange happens for ~59 minutes on a typical IdP default.
  • Shared cache between processes — pass a PSR-16 cache (cache : argument) and the token is written there and read back first : one exchange per token lifetime for the whole application, not one per request. 🔒 The cache holds the token in clear : keep it private to the server.
  • Reactive retry on 401 — if the resource API rejects the cached Bearer (clock drift, premature revocation), the client invalidates its cache (the shared one too), performs one fresh exchange, and replays the request once. If the retry still fails with 401, a KeyfileInvalidException is thrown.
  • Final 401 are not retried — a 401 whose reason says the identity itself is refused (service_inactive, service_expired, account_disabled : FINAL_UNAUTHORIZED_REASONS) raises an ApiResponseException at once.
  • Other failures raise at once — only a 401 triggers the refresh-and-retry ; every other non-2xx answer raises an ApiResponseException, never masked by a useless re-exchange.

See documentation/en/token-lifecycle.md for the full sequence diagram.

⚠️ Error handling

use oihana\m2m\M2MApiClient;
use oihana\m2m\exceptions\ApiResponseException;
use oihana\m2m\exceptions\IdentityProviderUnavailableException;
use oihana\m2m\exceptions\KeyfileInvalidException;
use GuzzleHttp\Exception\GuzzleException;

try
{
    $data = $client->get( '/widgets' ) ;
}
catch( ApiResponseException $e )
{
    // The API answered something else than a 2xx.
    // $e->getStatusCode(), $e->getReason(), $e->getDetails() ; retry later only if $e->isRetryable().
}
catch( IdentityProviderUnavailableException $e )
{
    // The identity provider is down. Retry later : the keyfile is fine.
}
catch( KeyfileInvalidException $e )
{
    // The keyfile is refused. Action : ask for a fresh keyfile.
}
catch( GuzzleException $e )
{
    // Network failure with the API (timeout, DNS, TLS, …). Retry later.
}

Every exception of the library extends oihana\m2m\exceptions\M2MException.

See documentation/en/error-handling.md.

🧩 Extending the client

call(), doRequest(), decodeResponse(), buildUrl(), isFinalUnauthorized(), readRetryAfter() and toApiResponseException() are protected extension hooks. Subclass M2MApiClient to add per-request instrumentation, correlation IDs, tenant headers, or to support non-JSON envelopes — without rewriting the public verb methods.

class TracingM2MClient extends M2MApiClient
{
    protected function doRequest( string $method , string $url , ?array $body , #[\SensitiveParameter] string $token ) :\Psr\Http\Message\ResponseInterface
    {
        $started  = microtime( true ) ;
        $response = parent::doRequest( $method , $url , $body , $token ) ;
        $this->logger->info( "M2M $method $url" , [ 'status' => $response->getStatusCode() , 'ms' => ( microtime( true ) - $started ) * 1000 ] ) ;
        return $response ;
    }
}

See documentation/en/advanced/extending-the-client.md.

📚 Documentation

Full documentation is available in two languages :

Topics covered:

  • Getting started — install + first call in under 2 minutes.
  • Keyfile format — full field reference, security considerations.
  • Token lifecycle — caching, proactive refresh, reactive retry on 401.
  • Error handling — exception catalogue + recommended recovery actions.
  • Tips & best practices — typed constants to avoid magic strings.
  • Upgrading — from 1.x to 2.0.
  • Advanced — HTTP client injection, subclassing for instrumentation, non-Zitadel IdPs.

🧪 Running the tests

composer install
composer test      # PHPUnit
composer analyse   # PHPStan, level max

The unit suite covers the constructor contract and the fromKeyfile factory, and the critical path without any network : the signed assertion (checked with the public key), the token exchange and its cache, the shared cache (PSR-16, with a failing cache), the retry on a stale token, every exception, the request paths and the masking of the secrets — with Guzzle's MockHandler and an RSA key generated for the run.

🛠 Generating the API documentation

composer doc

Generates the phpDocumentor API reference into docs/.

🪪 License

This project is licensed under the Mozilla Public License 2.0 (MPL-2.0).

👤 Author

Marc Alcaraz (@BcommeBois) — Project Founder, Lead Developer

🔗 Related libraries

Not required by this library — optional companions for a broader catalogue of constants and schemas.