Search by

adachsoft / oidc-provider-contracts

Arkadiusz Adach

Framework-independent OpenID Connect and OAuth 2.0 provider contracts, models, and flow services.

Package info

gitlab.com/a.adach/oidc-provider-contracts

Issues

pkg:composer/adachsoft/oidc-provider-contracts

Statistics

Installs: 7

Dependents: 1

Suggesters: 0

Stars: 0

v0.1.0 2026-11-26 18:45 UTC

This package is auto-updated.

Last update: 2026-11-26 17:46:02 UTC


README

adachsoft/oidc-provider-contracts provides framework-independent models, repository contracts, and token-issuance services for an OpenID Connect and OAuth 2.0 provider. It defines signing-key lifecycle and token-signing abstractions without implementing HTTP endpoints, persistent storage, key generation, cryptography, or JWT signing and verification.

Authentication happens before this library is used. The provider receives an authenticated account identifier and records the client and grant state needed by its adapters.

Requirements

  • PHP 8.3 or newer.
  • Composer.
  • adachsoft/access-control-contracts, adachsoft/auth-contracts, adachsoft/collection, and psr/clock (installed as package dependencies).

Installation

composer require adachsoft/oidc-provider-contracts

Usage

Create DTOs and use the repository interfaces from provider logic. Production adapters can implement these interfaces for persistent storage; the included in-memory repositories are intended for tests and short-lived processes, not production persistence. Persistent adapters must provide the atomicity guarantees documented by each repository interface.

Flows

Client registration and authentication

ClientService registers clients from ClientRegistrationDto. Confidential clients receive a generated plaintext secret once in RegisteredClientDto; the repository stores only its TokenHash. Public clients receive no secret. Administrators can rotate a confidential secret and activate or deactivate clients. authenticate() returns an active client only when its credentials are valid. All client-authentication failures use the same safe invalid_client description.

Authorization-code requests

AuthorizationService::validate() checks the client and redirect target before validating OAuth parameters. The supplied redirect_uri must be syntactically valid and match one registered URI character-for-character; trailing-slash, case, and query-string differences are not accepted. If the client is unknown or inactive, or the redirect target is invalid or unregistered, the service throws InvalidRedirectionTargetException, which is deliberately not an OAuth exception. The HTTP layer must show a local error page and must not redirect in that case.

Only after the redirect target is trusted can an AbstractOAuthException be mapped to an OAuth error redirect. The HTTP layer may send the error and the original state to the already-verified redirect URI. Public clients must use PKCE with S256; confidential clients may omit PKCE but cannot use another method. Validated scopes are limited to the client's allowed scopes, state is preserved unchanged, and nonce is stored with the authorization code. issueCode() requires an existing active account, returns the plaintext code once, and persists only its hash until the configured authorization-code lifetime expires.

OAuth exception to protocol error mapping:

ExceptionOAuth error
InvalidRequestExceptioninvalid_request
InvalidClientExceptioninvalid_client
InvalidGrantExceptioninvalid_grant
UnauthorizedClientExceptionunauthorized_client
UnsupportedGrantTypeExceptionunsupported_grant_type
UnsupportedResponseTypeExceptionunsupported_response_type
InvalidScopeExceptioninvalid_scope
AuthorizationPendingExceptionauthorization_pending
SlowDownExceptionslow_down
AccessDeniedExceptionaccess_denied
ExpiredTokenExceptionexpired_token

InvalidRedirectionTargetException is not in this table because it must never be redirected to a client-controlled URI.

Reused contracts

This package does not redefine identities or token hashes:

  • AccountId comes from adachsoft/access-control-contracts.
  • TokenHash comes from adachsoft/auth-contracts; only hashes of authorization codes, device codes, and refresh tokens are stored.
  • Immutable collections come from adachsoft/collection.
  • psr/clock is available to consumer implementations for time-dependent provider logic.

Models and services in this stage

  • Client IDs, exact redirect URIs, OAuth scopes, device user codes, and S256 PKCE challenges.
  • Client registrations with client type, allowed grants and scopes, redirect URIs, optional service account, active state, and optimistic version.
  • Authorization-code, device-authorization, and refresh-token records, including device approval and refresh rotation/revocation transitions.
  • Signing-key identifiers and ES256 signing-key records, with active/retired states and optimistic versions.
  • Provider lifetime policy, token-verification expectations, and issued access-token, ID-token, and refresh-token DTOs.
  • Client, grant, refresh-token, and signing-key repository interfaces with in-memory implementations for tests and short-lived processes.

Client, device, and signing-key repository updates use optimistic version checks. Authorization-code and approved device-authorization consumption must be atomic and single-use. Refresh-token family revocation must be atomic. In-memory repositories provide these guarantees within one process; persistent adapters must provide equivalent guarantees using transactions, locks, or another suitable storage primitive.

Repository contract tests

The abstract PHPUnit contracts in testing/ can be extended by persistent repository adapters. Install PHPUnit in the consuming project's development dependencies, then implement the corresponding repository factory:

use AdachSoft\OidcProviderContracts\Interface\ClientRepositoryInterface;
use AdachSoft\OidcProviderContracts\Testing\AbstractClientRepositoryContractTest;

final class DatabaseClientRepositoryContractTest extends AbstractClientRepositoryContractTest
{
    protected function createRepository(): ClientRepositoryInterface
    {
        return new DatabaseClientRepository(/* adapter dependencies */);
    }
}

The same pattern is available through AbstractAuthorizationCodeRepositoryContractTest, AbstractDeviceAuthorizationRepositoryContractTest, AbstractRefreshTokenRepositoryContractTest, and AbstractSigningKeyRepositoryContractTest. The in-memory implementations are exercised by concrete tests in this package.

Signing keys and rotation

SigningKeyService creates the first ES256 key on demand, retires the current key during rotation, and exposes active keys plus retired keys within the configured retention window. The repository contract requires unique key IDs, optimistic version checks, and at most one active key. Retired keys can be pruned after their publication period. The default RandomKeyIdGenerator creates URL-safe identifiers; a SigningKeyGeneratorInterface adapter must provide the actual key material. Private key material is read through SigningKeyDto::privateKey() (for signer adapters) and omitted from var_dump/print_r output.

Token abstractions

TokenSignerInterface and TokenVerifierInterface define compact JWS signing and verification without providing a JWT implementation. A signer must include kid, alg, and typ: JWT in the protected header. Verification receives published keys and a TokenExpectationDto for issuer, audience, time, and leeway checks; failures use InvalidTokenException with an InvalidTokenReasonEnum reason.

TokenIssuer creates access tokens with client and subject claims, ID tokens with optional nonce and scope-filtered account claims, and opaque refresh tokens. Refresh-token persistence stores only the TokenHash; the plaintext token is returned to the caller once. Application-provided ClaimsProviderInterface implementations decide which profile or email claims are available for the granted scopes.

TokenService

TokenService::exchangeAuthorizationCode() requires the authorization-code grant and consumes each code once. It checks the code's client, exact redirect URI, optional S256 PKCE verifier, and active account before issuing an access token. An ID token is included only when the granted scopes contain openid; a refresh token is issued only when the client allows the refresh-token grant.

TokenService::clientCredentials() requires the client-credentials grant and a configured active service account. A missing or empty scope selects all client-allowed scopes; otherwise the requested scopes must be allowed. The openid scope is not valid for this grant. The service account is the access token subject, and the response contains neither an ID token nor a refresh token.

TokenService::refresh() requires the refresh-token grant and rotates each token into a replacement in the same family. A request may narrow the token's scopes but cannot expand them. Reuse of a rotated token is treated as token theft: the whole family, including its current token, is revoked and the request fails with invalid_grant. Refresh responses deliberately do not include an ID token, even when the retained scopes contain openid.

Device authorization (RFC 8628)

DeviceAuthorizationService::start() authenticates a client with the device-code grant, validates the requested scopes, and returns a one-time plaintext device code with a formatted user code, expiry, and polling interval. Only the device-code hash is persisted. The application verification page can look up an unexpired pending request with findPending(), then call approve() for an existing active account or deny(). The configured policy supplies the device-code lifetime and initial polling interval.

TokenService::deviceCode() implements the RFC 8628 polling responses: pending requests return authorization_pending, early polls increase the interval and return slow_down, denied requests return access_denied, and expired requests return expired_token. Approved requests are consumed once. They issue an access token and, when the client also allows the refresh-token grant, a refresh token. Device authorization responses deliberately do not include an ID token.

The application must rate-limit attempts on the user-code verification page. User codes are guessable by brute force if that page is not rate-limited. This library provides the authorization contracts and flow services, not the HTTP page or its rate limiter.

Discovery and JWKS

DiscoveryDocumentFactory creates OpenID Provider Metadata from the configured issuer, supported scopes, and validated absolute endpoint URLs. Endpoints must use HTTPS, except HTTP is allowed for localhost and 127.0.0.1 in development. The optional UserInfo endpoint is omitted when it is not configured.

JwksDocumentFactory builds a public-only JWKS from published signing keys and adds each key's kid, alg, and use: sig metadata. Private key material and private JWK members are never included in the document.

TokenResponseDto::toArray() serializes the response with the RFC 6749 access_token, token_type, expires_in, and space-delimited scope fields. id_token and refresh_token are included only when issued.

Required adapters

Production integrations must provide persistent implementations of the repository interfaces, a key-generation adapter for ES256, and token signer and verifier adapters backed by an established JWT library. The application supplies scope-filtered account claims through ClaimsProviderInterface. Time comes from PSR-20 ClockInterface, and opaque token values come from adachsoft/auth-contracts TokenGeneratorInterface. The included in-memory repositories are intended for tests and short-lived processes, not production persistence.