adachsoft / oauth-client-lib
Pure PHP OAuth 2.0 and 2.1 client with PKCE, token lifecycle management, and automatic token refresh.
Requires
- php: >=8.3
- adachsoft/collection: ^3.0
- guzzlehttp/guzzle: ^7.8
Requires (Dev)
- adachsoft/php-code-style: ^0.7.4
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^12.5
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A framework-independent PHP client for OAuth 2.0/2.1 authorization-server discovery, Authorization Code with PKCE, token refresh, and provider-specific token storage.
Capabilities
- Discover authorization-server metadata from an issuer or protected-resource URL.
- Build Authorization Code requests using PKCE with
S256and CSRFstate. - Exchange authorization codes and refresh tokens through a replaceable HTTP client.
- Store provider-specific tokens in environment files or in memory, and refresh tokens before expiry.
- Use the library independently of an application framework.
Requirements
- PHP 8.3 or later
- Guzzle 7.8 or later
adachsoft/collection3.x
Installation
Install the library in a Composer project:
composer require adachsoft/oauth-client-lib
In an application, create a token storage and OAuth client, discover the provider metadata, and use the client for authorization and token lifecycle operations. See the integration example for a complete flow.
Usage
The following flow discovers provider endpoints, completes an interactive PKCE login, and retrieves a valid access token.
Quick start
Create token storage and the default client. The provider identifier determines the default environment-variable prefix; for example, playgama maps to PLAYGAMA_*.
use AdachSoft\OAuthClientLib\Factory\OAuthClientFactory;
use AdachSoft\OAuthClientLib\Storage\EnvOAuthTokenStorage;
use AdachSoft\OAuthClientLib\ValueObject\OAuthProviderIdVo;
$provider = new OAuthProviderIdVo('playgama');
$storage = new EnvOAuthTokenStorage(__DIR__ . '/.env');
$oauthClient = OAuthClientFactory::createDefault($storage);
Discover the authorization-server metadata using either its issuer URL or a protected-resource URL:
$metadata = $oauthClient->discoverMetadata('https://resource.example.test/api/mcp');
The returned OAuthServerMetadataDto contains the validated authorization and token endpoints. Register the public client identifier and redirect URI with the authorization server before starting login.
Run the interactive Authorization Code with PKCE flow:
use AdachSoft\OAuthClientLib\Collection\OAuthScopeVoCollection;
use AdachSoft\OAuthClientLib\Factory\OAuthClientFactory;
use AdachSoft\OAuthClientLib\ValueObject\OAuthScopeVo;
$login = OAuthClientFactory::createLoginCliRunner($storage);
$exitCode = $login->run(
$metadata->authorizationEndpoint,
$metadata->tokenEndpoint,
'registered-public-client-id',
'http://127.0.0.1/callback',
new OAuthScopeVoCollection([new OAuthScopeVo('mcp')]),
$provider,
);
if ($exitCode !== 0) {
throw new RuntimeException('OAuth authorization failed.');
}
The runner prints the authorization URL and prompts for the callback URL or authorization code. Prefer pasting the complete callback URL: the runner validates its state before exchanging the code. The runner stores the returned tokens and does not print authorization codes or token values.
Use a stored token and refresh it when necessary:
$token = $oauthClient->getValidToken(
$provider,
$metadata->tokenEndpoint,
'registered-public-client-id',
);
$authorizationHeader = $token->tokenType . ' ' . $token->accessToken;
getValidToken() refreshes a token that is expired or near expiry when a refresh token is available, and persists the updated token through the configured storage.
Token storage
EnvOAuthTokenStorage reads a dotenv-compatible file and the current process environment. Non-empty process values in $_ENV, $_SERVER, or getenv() take precedence over values from the file. Saving updates the file under an exclusive lock and synchronizes the current PHP process environment.
For the playgama provider, the default keys are:
PLAYGAMA_ACCESS_TOKENPLAYGAMA_REFRESH_TOKENPLAYGAMA_EXPIRES_AT(Unix timestamp)PLAYGAMA_TOKEN_TYPE(defaults toBearer)PLAYGAMA_SCOPE
An optional prefix can be supplied to EnvOAuthTokenStorage when a different key namespace is required. InMemoryOAuthTokenStorage is available for tests and non-persistent use.
Environment files containing OAuth credentials are secrets: restrict file permissions, exclude them from version control, and never print or log their contents. Prefer a dedicated secret store for production deployments when available.
Security and scope
- Authorization requests use PKCE with
S256and a cryptographically generatedstateunless the caller supplies one. - Token responses and credential-bearing HTTP response bodies are not included in exception messages.
- The library does not host a browser callback server. The CLI runner requires a user to open the authorization URL and provide the callback URL or code.
- The library does not register OAuth clients automatically; the client identifier and redirect URI must be provisioned by the authorization server or application.
OAuthTokenStorageInterfacecan be implemented for a database, operating-system key store, or another application-specific secure backend.
Development checks
Run the package PHPUnit suite:
vendor/bin/phpunit --configuration=packages/oauth-client-lib/phpunit.xml
Run the live Playgama OAuth discovery smoke test only when network access is available:
vendor/bin/phpunit --configuration=packages/oauth-client-lib/phpunit.xml --group=playgama-production
Run PHPStan with the repository configuration:
vendor/bin/phpstan analyse packages/oauth-client-lib/src packages/oauth-client-lib/tests --configuration=phpstan.neon