PHPackages                             centralauth/oauth2-centralauth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. centralauth/oauth2-centralauth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

centralauth/oauth2-centralauth
==============================

CentralAuth OAuth 2.0 provider for league/oauth2-client

v1.2.0(5mo ago)042MITPHPPHP &gt;=8.1CI passing

Since Oct 6Pushed 5mo agoCompare

[ Source](https://github.com/CentralAuth/CentralAuth-PHP-library)[ Packagist](https://packagist.org/packages/centralauth/oauth2-centralauth)[ RSS](/packages/centralauth-oauth2-centralauth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (8)Used By (0)

CentralAuth OAuth2 Provider for league/oauth2-client
====================================================

[](#centralauth-oauth2-provider-for-leagueoauth2-client)

[![Packagist Version](https://camo.githubusercontent.com/274d156d92d0929bd7a3630e01b5a903e2790e617b45b5625143f7a4aaeb4198/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63656e7472616c617574682f6f61757468322d63656e7472616c617574682e737667)](https://packagist.org/packages/centralauth/oauth2-centralauth)[![License](https://camo.githubusercontent.com/20ba9f36fb642641974e66ecb4f2ee8a2c5aca2fcfdf482e49016c1f1ec28bb1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f63656e7472616c617574682f6f61757468322d63656e7472616c617574682e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/6b6dbf5a7e9c33aea140ba545731ce4cc69ea602e84f2bcdc4247fd964c5b142/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f63656e7472616c617574682f6f61757468322d63656e7472616c617574682e737667)](https://www.php.net/)

> A lightweight, focused OAuth 2.0 provider for integrating CentralAuth with the PHP League's [`league/oauth2-client`](https://github.com/thephpleague/oauth2-client). It wraps CentralAuth-specific behavior so your application code stays clean and portable.

---

🎯 Live Demo
-----------

[](#-live-demo)

A demo implementation is available at  ([source code](https://github.com/CentralAuth/CentralAuth-PHP-example)).

---

✨ Features
----------

[](#-features)

- Authorization Code flow (incl. PKCE support inherited from base library)
- CentralAuth-specific user info retrieval
- Automatic Basic auth header for user info (clientId:clientSecret)
- Adds `?domain=` query parameter to user info endpoint
- Custom headers automatically included: `auth-ip`, `user-agent`
- Small surface area – minimal assumptions, easy to extend

---

✅ Requirements
--------------

[](#-requirements)

ComponentVersionPHP8.1+league/oauth2-client^2.8---

📦 Install
---------

[](#-install)

```
composer require centralauth/oauth2-centralauth
```

---

🔧 Configuration Options
-----------------------

[](#-configuration-options)

OptionRequiredDescription`client_id`YesCentralAuth OAuth client ID`client_secret`YesCentralAuth OAuth client secret`redirect_uri`YesYour app callback URL (must match configured value)`authorization_url`YesCentralAuth login/authorization endpoint`token_url`YesCentralAuth token/verify endpoint`resource_owner_details_url`YesCentralAuth user info endpoint`domain`NoOverrides domain passed as `?domain=` (defaults to `redirect_uri`)---

🚀 Quick Start
-------------

[](#-quick-start)

```
use CentralAuth\OAuth2\Client\Provider\CentralAuth;

session_start(); // required for state persistence

$provider = new CentralAuth([
  'clientId' => getenv('CENTRALAUTH_CLIENT_ID'),
  'clientSecret' => getenv('CENTRALAUTH_CLIENT_SECRET'),
  'redirectUri' => 'https://your-app.example/oauth/callback',
  'authorization_url' => 'https://centralauth.com/login',
  'token_url' => 'https://centralauth.com/api/v1/verify',
  'resource_owner_details_url' => 'https://centralauth.com/api/v1/userinfo'
]);

if (!isset($_GET['code'])) {
  $authUrl = $provider->getAuthorizationUrl();
  $_SESSION['oauth2state'] = $provider->getState();
  header('Location: ' . $authUrl);
  exit;
}

if (empty($_GET['state']) || $_GET['state'] !== ($_SESSION['oauth2state'] ?? null)) {
  unset($_SESSION['oauth2state']);
  exit('Invalid state');
}

$token = $provider->getAccessToken('authorization_code', [
  'code' => $_GET['code']
]);

$resourceOwner = $provider->getResourceOwner($token);
$user = $resourceOwner->toArray();

// Use $user['email'], $user['id'], etc.
```

---

🧠 Why Not `GenericProvider`?
----------------------------

[](#-why-not-genericprovider)

CentralAuth requires a **non-standard user info retrieval pattern**:

1. HTTP Method: `POST`
2. Body: raw access token string (not JSON, not form-encoded)
3. Headers:
    - `Authorization: Basic base64(clientId:clientSecret)`
    - `auth-ip: `
    - `user-agent: `
4. `?domain=` query parameter appended to the user info URL

`GenericProvider` would require re-implementing this logic inline for every project—this package encapsulates it cleanly.

---

👤 Resource Owner
----------------

[](#-resource-owner)

Example returned fields:

```
{
  "id": "12345",
  "email": "user@example.com",
  "gravatar": "https://www.gravatar.com/avatar/..."
}
```

Provided helpers:

```
$owner = $provider->getResourceOwner($token);
$owner->getId();
$owner->getEmail();
$owner->getGravatar();
$owner->toArray();
```

---

⚠️ Error Handling
-----------------

[](#️-error-handling)

`checkResponse()` normalizes HTTP errors. An `IdentityProviderException` is thrown containing:

- Exception message (error / error\_description / raw body)
- HTTP status code
- Original response instance

Wrap sensitive operations:

```
try {
  $token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  // Log and surface user-friendly message
}
```

---

🧪 Testing
---------

[](#-testing)

This library includes comprehensive PHPUnit tests covering all functionality:

### Quick Test Validation

[](#quick-test-validation)

For a quick syntax and structure check:

```
./test-runner.sh
```

### Test Commands

[](#test-commands)

```
# Run all tests (44 tests, fast and clean)
composer test

# Run only unit tests (37 tests)
composer test-unit

# Run only integration tests (7 tests)
composer test-integration

# Generate coverage report (requires Xdebug or PCOV)
composer test-coverage
```

### Test Coverage

[](#test-coverage)

The test suite includes:

- **Unit tests**: Individual class and method testing (CentralAuth, CentralAuthResourceOwner)
- **Integration tests**: Complete OAuth2 workflow testing
- **Error handling**: Various error scenarios and edge cases
- **No external dependencies**: All HTTP calls are mocked for reliable testing

For detailed testing instructions, see [TESTING.md](TESTING.md).

---

🛡 Security
----------

[](#-security)

Do NOT publish real credentials in code or VCS. Report vulnerabilities privately.

---

📄 License
---------

[](#-license)

Released under the [MIT License](LICENSE).

---

📚 Documentation
---------------

[](#-documentation)

For complete CentralAuth documentation and API reference, visit the [official docs](https://docs.centralauth.com).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance70

Regular maintenance activity

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~10 days

Total

6

Last Release

171d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.4

v1.2.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/52db622d47c4739a14ae5376b8eb5410b0b5ea34e6db93b6d6fe3f0142595675?d=identicon)[West IT](/maintainers/West%20IT)

---

Top Contributors

[![JWW87](https://avatars.githubusercontent.com/u/39670111?v=4)](https://github.com/JWW87 "JWW87 (25 commits)")

---

Tags

AuthenticationSSOoauth2centralauth

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/centralauth-oauth2-centralauth/health.svg)

```
[![Health](https://phpackages.com/badges/centralauth-oauth2-centralauth/health.svg)](https://phpackages.com/packages/centralauth-oauth2-centralauth)
```

###  Alternatives

[adam-paterson/oauth2-stripe

Stripe OAuth 2.0 Client Provider for The PHP League OAuth2-Client

172.4M4](/packages/adam-paterson-oauth2-stripe)[adam-paterson/oauth2-slack

Slack OAuth 2.0 Client Provider for The PHP League OAuth2-Client

22694.8k5](/packages/adam-paterson-oauth2-slack)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
