Skip to content
CAI
Software that uses CAICheck a score

thephpleague/oauth2-server

77.6

Strong · 19 September 2026

5.6k

lines of production code

PHP

primary language

1

measurement over time

CAI band scale
CAI lens gauges

What this system is

This system is a PHP library implementing an OAuth 2.0 authorization and resource server. It manages the full lifecycle of access tokens, authorization codes, and refresh tokens across various grant types, including the Device Code flow. The library provides PSR-15 middleware for integration, enforces security standards like PKCE and RFC 8252, and handles cryptographic operations for token encryption and validation.

How it got here

2012–2015 — OAuth 2.0 server implementation

13 changes.

This period established the foundational structure of the league/oauth2-server library, initializing the repository with comprehensive documentation, CI/CD tooling, and MIT licensing. The core development focused on implementing RFC-compliant OAuth 2.0 authorization and resource server components, including grant types, token management, and encryption via Defuse Crypto. Extensive unit tests and example applications were added to validate the new architecture and demonstrate usage patterns for various grant flows.

2016–2022 — OAuth2 specification compliance and middleware integration

16 changes.

This period focused on modernizing the library's core architecture to align with current OAuth 2.0 standards, including the introduction of PSR-15 middleware, PKCE support, and RFC 8252-compliant redirect URI validation. Significant refactoring was applied to entity interfaces and JWT validation to improve type safety and security, while comprehensive test coverage was added for new features and existing components.

Features

Added PKCE code challenge verifiers for plain and S256 methods

The library now supports Proof Key for Code Exchange (PKCE) by introducing a new \CodeChallengeVerifierInterface\ and two implementations: \PlainVerifier\ for the 'plain' method and \S256Verifier\ for the 'S256' method. These components allow the OAuth2 server to verify code challenges sent by clients, enhancing security for public clients during the authorization code flow.

src/CodeChallengeVerifiers · high confidence

Added example entity implementations for OAuth2 server components

The examples directory now includes concrete entity classes for the OAuth2 server, providing ready-to-use implementations for AccessToken, AuthCode, Client, DeviceCode, RefreshToken, Scope, and User entities. These classes implement the respective interfaces from the League OAuth2 Server library and utilize standard traits (such as AccessTokenTrait, ClientTrait, and ScopeTrait) to handle common functionality, with the ClientEntity additionally exposing methods to set the name, redirect URI, and confidential status.

examples/src/Entities · high confidence

Initial project scaffolding and documentation

The repository is initialized with standard project files, including a comprehensive README detailing supported OAuth 2.0 grants and PHP versions, a CHANGELOG following the Keep a Changelog format, and a MIT LICENSE. Development tooling is configured via \.gitattributes\ and \.gitignore\ to manage exports and local artifacts, while CI/CD and code quality are set up with \.scrutinizer.yml\, \.styleci.yml\, \phpunit.xml.dist\, \phpstan.neon.dist\, and \phpcs.xml.dist\. Community guidelines are established through \CONTRIBUTING.md\ and \CODE\_OF\_CONDUCT.md\.

(repo-wide) · high confidence

Introduce AuthorizationRequestInterface and AuthorizationRequest class

Added a new \AuthorizationRequestInterface\ and its implementation \AuthorizationRequest\ in the \src/RequestTypes\ namespace. This provides a structured data carrier for OAuth 2.0 authorization requests, exposing properties and accessors for the grant type, client, user, scopes, authorization status, redirect URI, state, and PKCE code challenge details.

src/RequestTypes · high confidence

Introduction of internal event emission infrastructure

The library now includes a dedicated event emission system within the \EventEmitting\ namespace, introducing \AbstractEvent\ as the base class for events (implementing \StoppableEventInterface\ and \HasEventName\), an \EventEmitter\ class that wraps \League\\Event\\EventDispatcher\, and an \EmitterAwarePolyfill\ trait to allow classes to easily integrate with this emitter. This provides a standardized way for the OAuth2 server to emit and handle events, replacing or supplementing previous mechanisms.

src/EventEmitting · high confidence

New PSR-15 middleware for OAuth2 authorization and resource server validation

Two new middleware classes have been added to the library: AuthorizationServerMiddleware and ResourceServerMiddleware. AuthorizationServerMiddleware wraps the AuthorizationServer to handle access token requests, converting OAuthServerException into HTTP responses. ResourceServerMiddleware wraps the ResourceServer to validate authenticated requests on protected resources, also ensuring exceptions are properly converted to HTTP responses. Both implement the PSR-15 middleware interface, allowing them to be easily integrated into PSR-15 compatible HTTP servers.

src/Middleware · high confidence

New entity traits for OAuth2 token and client management

This change introduces a suite of new PHP traits in src/Entities/Traits to standardize and simplify the implementation of OAuth2 entities. AccessTokenTrait now handles JWT generation using lcobucci/jwt v4, including private key management and sensitive parameter attributes. DeviceCodeTrait adds support for the Device Code grant flow, allowing configuration of polling intervals and verification URIs. ClientTrait provides base properties for client name, redirect URIs, and confidentiality status. TokenEntityTrait and RefreshTokenTrait manage common token properties like scopes, expiry, and user identifiers, while EntityTrait, AuthCodeTrait, and ScopeTrait provide foundational methods for identifiers, redirect URIs, and JSON serialization.

src/Entities/Traits · high confidence

Behavioural changes

Bearer token validation now uses lcobucci/jwt 4.x with configurable date leeway

The BearerTokenValidator has been rewritten to use the lcobucci/jwt 4.x API, replacing the previous implementation. This change introduces a configurable leeway for validating JWT expiration and 'not before' dates via the new constructor parameter, and enforces stricter validation by ensuring the parsed token is an UnencryptedToken instance. The validator now also properly chains exceptions from the JWT library and checks for token revocation against the access token repository before attaching OAuth attributes to the request.

src/AuthorizationValidators · high confidence

New OAuthServerException class with spec-compliant error handling

The library introduces a new \OAuthServerException\ class that standardizes OAuth 2.0 error responses. This class provides static factory methods for common errors (such as \invalidRequest\, \invalidClient\, \invalidScope\, \invalidCredentials\, \serverError\, \invalidRefreshToken\, and \accessDenied\) and ensures responses include the correct HTTP status codes and error types. It also supports redirect URIs for authorization errors and includes a \UniqueTokenIdentifierConstraintViolationException\ for token generation failures. Users will see more consistent, RFC-compliant error messages and status codes in API responses.

src/Exception · high confidence

New RFC 8252-compliant loopback redirect URI validation

The OAuth2 server now includes a new \RedirectUriValidator\ that strictly validates redirect URIs using the \league/uri\ library. For standard URIs, it performs an exact match against the allowed list. For loopback URIs (127.0.0.1 or \[::1\] on HTTP), it implements RFC 8252 section 7.3 compliance by matching the scheme, host, and path while ignoring the port number, allowing clients to use dynamic local ports. This replaces previous validation logic with a more robust, standards-compliant approach.

src/RedirectUriValidators · high confidence

OAuth 2.0 grant implementations refactored with encrypted tokens and PKCE support

The grant classes in src/Grant have been rewritten to enforce stricter OAuth 2.0 compliance and security. Refresh tokens are now encrypted payloads rather than JWTs, requiring decryption during validation in RefreshTokenGrant. The Authorization Code Grant now fully implements PKCE (RFC 7636), validating code challenges and verifiers, and enforces PKCE for public clients by default. The Device Code Grant introduces new device authorization flows with configurable polling intervals and verification URIs. Client validation is centralized in AbstractGrant, ensuring confidential clients must provide a secret and public clients are restricted from using the Client Credentials grant. Additionally, grants now emit specific events for token issuance and client authentication failures.

src/Grant · high confidence

OAuth2 entity interfaces restructured and expanded

The entity contract layer in src/Entities has been refactored to provide stricter, more explicit interfaces for OAuth2 components. TokenInterface now mandates DateTimeImmutable for expiry handling and enforces string-based identifiers, while AccessTokenEntityInterface introduces a dedicated toString() method for serialization. New interfaces have been added to support the Device Code grant flow (DeviceCodeEntityInterface) and to standardize client metadata (ClientEntityInterface), and RefreshTokenEntityInterface now explicitly links to access tokens. These changes tighten the API contracts for token and client entities, improving type safety and enabling new grant types.

src/Entities · high confidence

OAuth2 repository interfaces restructured and expanded

The repository layer for OAuth2 token and client storage has been refactored, introducing new interfaces for access tokens, auth codes, device codes, and refresh tokens, while updating the client, scope, and user repository interfaces. This change modifies the contract for implementing custom storage backends, notably adding grant type and client entity parameters to user credential validation, allowing scopes to be finalized with an optional auth code ID, and enabling device code support, which requires implementations to update their methods to match the new signatures.

src/Repositories · high confidence

OAuth2 server core classes and encryption refactoring

The library introduces a new \AuthorizationServer\ class to manage grant types and authorization flows, alongside a \ResourceServer\ for validating access tokens. Cryptographic operations are now handled via the \CryptKey\ class and \CryptTrait\, which migrate encryption from key-based methods to the \Defuse\\Crypto\ library, supporting both \Defuse\\Crypto\\Key\ objects and password strings. The server now emits new events (\access\_token.issued\, \refresh\_token.issued\, etc.) via \RequestEvent\ subclasses, and enforces stricter key validation and permission checks.

src · high confidence

Refactor OAuth2 response types to use encryption and support Device Code grant

The response type classes in src/ResponseTypes have been restructured to improve security and extend grant support. BearerTokenResponse now encrypts the refresh token payload using the provided encryption key instead of relying on JWT, and includes custom fields via a new getExtraParams method. A new DeviceCodeResponse class has been added to handle the Device Code grant flow, supporting optional inclusion of verification\_uri\_complete and interval parameters. The AbstractResponseType base class now manages access token, refresh token, and private key injection, while the ResponseTypeInterface defines the contract for setting encryption keys. RedirectResponse remains unchanged but is part of the new structure.

src/ResponseTypes · high confidence

Updated OAuth 2.0 example applications to use the new API

The example applications in the public directory have been rewritten to align with the latest library API. This includes adding a new API example that demonstrates securing endpoints with the Resource Server middleware, introducing a Device Code grant example, and updating existing examples (Authorization Code, Client Credentials, Implicit, Password, and Refresh Token) to use the new \respondToAccessTokenRequest\ method and updated grant configurations.

examples/public · high confidence

Updated example repository implementations to match new OAuth2 server interfaces

The example code in examples/src/Repositories has been updated to implement the latest OAuth2 server repository interfaces. This includes new or modified implementations for AccessToken, AuthCode, Client, DeviceCode, RefreshToken, Scope, and User repositories. Key changes include the ClientRepository now using password\_hash/password\_verify for secret validation and explicitly setting clients as confidential, the ScopeRepository adding logic in finalizeScopes to programmatically append the 'email' scope for user identifier 1, and the UserRepository accepting the ClientEntityInterface in getUserEntityByUserCredentials. These updates ensure the examples correctly demonstrate current best practices for client validation, scope finalization, and user credential handling within the OAuth2 server.

examples/src/Repositories · high confidence

Test coverage

Added PHPStan dynamic method return type extension for AbstractGrant; Added test stubs for OAuth2 server entities and traits; Added tests for Bearer and Device Code response types; Added tests for OAuth2 middleware components; Added tests for OAuthServerException behavior; Added unit tests for AuthorizationServer and ResourceServer; Added unit tests for BearerTokenValidator; Added unit tests for CryptKey and CryptTrait; Added unit tests for OAuth2 grant types and event polyfill; Added unit tests for Plain and S256 code challenge verifiers; Added unit tests for RedirectUriValidator.

Dependencies

Initial release of OAuth 2.0 server library with PHP 8.2+ support

This change introduces the initial version of the league/oauth2-server library, a lightweight OAuth 2.0 authorization and resource server. The package requires PHP 8.2 through 8.5 and relies on modern dependencies including league/uri ^7.8, lcobucci/jwt ^5.6, and defuse/php-encryption ^2.4. It also includes example applications in the examples/ directory, which depend on Slim ^3.12.3 and specific versions of PSR-7 implementations and JWT libraries for demonstration purposes.

(dependencies) · high confidence

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

How this codebase got here

Baseline

  • First survey — no prior run to compare against. CAI 78.

Lenses

  • Code Health 98
  • Architecture 91
  • Maturity 65
  • Readiness 85
  • Security 94

Changes since last survey

  • 300 commits — 193 feature/other, 107 fixes

By area

  • (root) — 86 commits
  • (repo) — 59 commits
  • src/Grant — 36 commits
  • tests/Grant — 24 commits
  • examples/src — 19 commits
  • src/Entities — 15 commits
  • src/Exception — 13 commits
  • .github/workflows — 8 commits
  • examples/public — 8 commits
  • src/Repositories — 8 commits
  • tests/AuthorizationServerTest.php — 5 commits
  • src/CryptKey.php — 4 commits
  • tests/Middleware — 4 commits
  • src/AuthorizationServer.php — 2 commits
  • src/AuthorizationValidators — 2 commits
  • src/CryptTrait.php — 2 commits
  • examples/README.md — 1 commit
  • src/CryptKeyInterface.php — 1 commit
  • src/EventEmitting — 1 commit
  • tests/AuthorizationValidators — 1 commit

Notable commits

  • fix: Fix CS issues
  • fix: Fix PHPStan errors
  • fix: Fix Implicitly marking parameter $param as nullable is deprecated
  • fix: Fix a test exception
  • fix: Fix all PHPStan errors
  • fix: Fix changelog error
  • fix: Fix coding standard issues
  • fix: Fix coding style
  • fix: Fix composer file
  • fix: Fix device code examples
  • fix: Fix docblock comment merge error
  • fix: Fix docblock return type
  • fix: Fix examples styling
  • fix: Fix explicit redirect uri not being optional in authorization code grant
  • fix: Fix format
  • fix: Fix import order
  • fix: Fix password grant example
  • fix: Fix phpstan errors
  • fix: Fix phpstan errors
  • fix: Fix reference to $this
  • …and 280 more

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

Survey your own repository

thephpleague/oauth2-server was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.

About this page

  • The score is its most recent published measurement, taken on 19 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
  • Measured at commit 9d2f6fc0a0b5aa1bb02506971d3a4ecff2c6526c — the exact code this score is about.
  • Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
  • Measured by watchdog.canine.dev using codehealth-analyzer preprod-13a154b7f5d1.