PHPackages                             blackcube/oauth2 - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. blackcube/oauth2

ActiveLibrary[HTTP &amp; Networking](/categories/http)

blackcube/oauth2
================

OAuth2/JWT toolbox with multi-population support

1.0.0(1mo ago)072↓86.7%1BSD-3-ClausePHPPHP ^8.1

Since May 11Pushed 1mo agoCompare

[ Source](https://github.com/blackcubeio/oauth2)[ Packagist](https://packagist.org/packages/blackcube/oauth2)[ Docs](https://github.com/blackcubeio/oauth2)[ RSS](/packages/blackcube-oauth2/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (19)Versions (3)Used By (1)

Blackcube OAuth2
================

[](#blackcube-oauth2)

OAuth2/JWT toolbox with multi-population support based on BShaffer oauth2 server.

[![License](https://camo.githubusercontent.com/6cb285b57819f8de0acfb34923298f4f569f962544e8fe35331da2d163f4e485/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4253442d2d332d2d436c617573652d626c75652e737667)](LICENSE.md)[![Packagist Version](https://camo.githubusercontent.com/27cf6495afefe26ec892401cdb575bbad477df827fc9c871cf91e0a16735f596/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f626c61636b637562652f6f61757468322e737667)](https://packagist.org/packages/blackcube/oauth2)

Installation
------------

[](#installation)

```
composer require blackcube/oauth2
```

Based On
--------

[](#based-on)

- [bshaffer/oauth2-server-php](https://github.com/bshaffer/oauth2-server-php) - OAuth2 engine ([documentation](https://bshaffer.github.io/oauth2-server-php-docs/))
- [lcobucci/jwt](https://github.com/lcobucci/jwt) - JWT handling

Philosophy
----------

[](#philosophy)

This package is a toolbox, not a turnkey solution. It provides interfaces and tools, never concrete implementations. The application that integrates it decides everything: storage, tables, business logic, routes.

**Principles:**

- Zero imposed tables
- Zero imposed storage (no MySQL/Redis in the package)
- Multi-population support (admin ≠ customer in the same app)
- DRY: scopes can be derived from an existing system (RBAC, config, API...)

Configuration
-------------

[](#configuration)

### params.php

[](#paramsphp)

```
return [
    'blackcube/oauth2' => [
        'name' => 'admin',
        'issuer' => 'myapp-admin',
        'audience' => 'myapi',
        'userQueryClass' => \App\Oauth2\AdminUser::class,
        'clientQueryClass' => \App\Oauth2\AdminClient::class,
        'refreshTokenQueryClass' => \App\Oauth2\AdminRefreshToken::class,
        'cypherKeyQueryClass' => \App\Oauth2\AdminCypherKey::class,
        'algorithm' => 'RS256',
        'accessTokenTtl' => 3600,        // 1h
        'refreshTokenTtl' => 2592000,    // 30 days
        'allowedGrants' => ['password', 'refresh_token'],
    ],
];
```

### di.php

[](#diphp)

```
use Blackcube\Oauth2\PopulationConfig;

return [
    PopulationConfig::class => [
        'class' => PopulationConfig::class,
        '__construct()' => $params['blackcube/oauth2'],
    ],
];
```

Interfaces to Implement
-----------------------

[](#interfaces-to-implement)

Your application must provide implementations for these interfaces per population:

InterfacePurpose`UserInterface`User entity with getId, getIdentifier, queryById, queryByIdentifier, queryByIdentifierAndPassword`ClientInterface`OAuth2 client entity with getId, getSecret, queryById, validateSecret`RefreshTokenInterface`Refresh token entity with save, revoke, queryByToken`ScopeProviderInterface`Available scopes, scopes per client`CypherKeyInterface`Signing keys (RSA/HMAC) with queryById, queryDefaultSupported Grants
----------------

[](#supported-grants)

GrantUsagepasswordUser login (mobile, SPA legacy)client\_credentialsService to Service (Node → PHP)authorization\_code + PKCEMobile, modern SPAsrefresh\_tokenToken renewalJWT Claims
----------

[](#jwt-claims)

```
{
    "sub": "123",
    "iss": "myapp-admin",
    "aud": "myapi",
    "exp": 1234567890,
    "iat": 1234567800,
    "scopes": ["category", "node", "order"]
}
```

ClaimDescriptionsubSubject - User IDissIssuer - Identifies the populationaudAudience - Token targetexpExpiration timestampiatIssued at timestampscopesGranted scopesAlgorithms
----------

[](#algorithms)

AlgorithmTypeUsageRS256Asymmetric**Default** - Multi-servicesRS384AsymmetricMore secure than RS256RS512AsymmetricMaximum securityHS256SymmetricSimple, shared secretHS384SymmetricMore secure than HS256HS512SymmetricMaximum symmetric security**Recommendation:** RS256/RS384/RS512 if multiple services validate tokens. HS\* only if everything stays in the same PHP process.

Key Generation
--------------

[](#key-generation)

### RSA (RS\*)

[](#rsa-rs)

```
# RS256/RS384/RS512 - 2048 bits key (minimum)
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

# RS512 - 4096 bits key (recommended)
openssl genrsa -out private.pem 4096
openssl rsa -in private.pem -pubout -out public.pem
```

### HMAC (HS\*)

[](#hmac-hs)

```
# Random 256 bits secret minimum
openssl rand -base64 32 > secret.key
```

Middleware Usage
----------------

[](#middleware-usage)

```
use Blackcube\Oauth2\Middlewares\JwtValidatorMiddleware;

// In your route configuration
Route::get('/api/protected')
    ->middleware(JwtValidatorMiddleware::class)
    ->action([ProtectedController::class, 'index']);
```

The middleware injects these attributes into the request:

- `jwt` - Full claims array
- `userId` - Subject (sub claim)
- `population` - Issuer (iss claim)
- `scopes` - Granted scopes array

What This Package Does NOT Do
-----------------------------

[](#what-this-package-does-not-do)

- Impose tables
- Impose storage (MySQL, Redis, etc.)
- Manage RBAC
- Decide routes
- Impose user/client structure
- Manage sessions
- Provide views (login, authorize, etc.)

License
-------

[](#license)

BSD-3-Clause. See [LICENSE.md](LICENSE.md).

Author
------

[](#author)

Philippe Gaultier

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance89

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

54d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/545714?v=4)[pgaultier](/maintainers/pgaultier)[@pgaultier](https://github.com/pgaultier)

---

Top Contributors

[![pgaultier](https://avatars.githubusercontent.com/u/545714?v=4)](https://github.com/pgaultier "pgaultier (2 commits)")

---

Tags

psr-7jwtmiddlewareAuthenticationtokenoauth2authorizationmulti-tenantrefresh-tokenmulti-population

###  Code Quality

TestsCodeception

### Embed Badge

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

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.7k147.0M289](/packages/league-oauth2-server)[cakephp/authentication

Authentication plugin for CakePHP

1214.1M106](/packages/cakephp-authentication)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28591.3k3](/packages/mezzio-mezzio-authentication-oauth2)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[mezzio/mezzio

PSR-15 Middleware Microframework

3923.8M126](/packages/mezzio-mezzio)

PHPackages © 2026

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