PHPackages                             monkeyscloud/monkeyslegion-auth - 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. monkeyscloud/monkeyslegion-auth

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

monkeyscloud/monkeyslegion-auth
===============================

High-performance authentication &amp; authorization: multi-guard, JWT, RBAC, OAuth, 2FA, API keys, passkeys

2.1.1(1w ago)12.0k↓38.3%[1 PRs](https://github.com/MonkeysCloud/MonkeysLegion-Auth/pulls)2MITPHPPHP ^8.4

Since Jul 23Pushed 1w agoCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Auth)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-auth)[ RSS](/packages/monkeyscloud-monkeyslegion-auth/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (1)Dependencies (28)Versions (16)Used By (2)

MonkeysLegion Auth v2
=====================

[](#monkeyslegion-auth-v2)

Multi-guard, attribute-first authentication and authorization for the MonkeysLegion framework. Ground-up rebuild for PHP 8.4 with property hooks, typed constants, and zero hard dependencies.

Features
--------

[](#features)

FeatureStatus**Multi-Guard System**JWT, Session, API Key, WebAuthn/Passkey, Composite (try multiple in order)**Attribute-First Auth**`#[Guard]`, `#[Authenticated]`, `#[Authorize]`, `#[RequiresRole]`, `#[RequiresPermission]`, `#[RateLimit]`, `#[Passkey]`**JWT Service**HS256/RS256, token families, refresh rotation attack detection**Session Guard**Session fixation prevention, token version validation, remember-me**Policy Gate**`allows()`, `denies()`, `authorize()`, `inspect()` with deny reasons**RBAC**Hierarchical roles, wildcard permissions, super-admin, decoupled via `RoleRepositoryInterface`**Password Hasher**NIST SP 800-63B policy engine, Argon2ID/bcrypt, auto-rehash**Rate Limiting**Per-route, per-user, configurable via attributes**Two-Factor Auth**TOTP (RFC 6238), backup/recovery codes**PSR-15 Middleware**Authentication, Authorization, Rate Limiting — all attribute-aware**PHP 8.4 Native**Property hooks, typed constants, `readonly` DTOsRequirements
------------

[](#requirements)

- **PHP 8.4** or higher
- `firebase/php-jwt` ^7.0
- `psr/http-message` ^2.0

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

[](#installation)

```
composer require monkeyscloud/monkeyslegion-auth:dev-2.0.0
```

Architecture
------------

[](#architecture)

```
src/
├── Attribute/          # #[Guard], #[Authenticated], #[Authorize], #[RequiresRole], #[RequiresPermission], #[RateLimit]
├── Contract/           # GuardInterface, StatefulGuardInterface, AuthenticatableInterface, SessionInterface, UserProviderInterface, ...
├── DTO/                # AuthResult, TokenPair, OAuthUser, PasswordPolicy
├── Event/              # AuthEvent, LoginSucceeded, LoginFailed, Logout, TokenRefreshed, ...
├── Exception/          # AuthException hierarchy with HTTP status codes and logging context
├── Guard/              # JwtGuard, SessionGuard, ApiKeyGuard, CompositeGuard, AuthManager
├── Middleware/          # AuthenticationMiddleware, AuthorizationMiddleware, RateLimitMiddleware
├── Policy/             # Gate (ability-based access control)
├── RBAC/               # RbacService, RoleRepositoryInterface, InMemoryRoleRepository
├── RateLimit/          # InMemoryRateLimiter
├── Service/            # AuthService, JwtService, PasswordHasher
├── Storage/            # InMemoryTokenStorage, InMemoryUserProvider, InMemorySession
├── Trait/              # AuthenticatableTrait, HasRolesTrait, HasPermissionsTrait
└── TwoFactor/          # TotpProvider

```

Quick Start
-----------

[](#quick-start)

### JWT Guard (Stateless)

[](#jwt-guard-stateless)

```
use MonkeysLegion\Auth\Guard\JwtGuard;
use MonkeysLegion\Auth\Guard\AuthManager;
use MonkeysLegion\Auth\Service\JwtService;

$jwt   = new JwtService('your-secret-key-at-least-32-chars');
$guard = new JwtGuard($jwt, $userProvider);

$manager = new AuthManager(defaultGuard: 'jwt');
$manager->register('jwt', $guard);

// Authenticate a request
$user = $manager->guard()->authenticate($request);
```

### Session Guard (Stateful)

[](#session-guard-stateful)

```
use MonkeysLegion\Auth\Guard\SessionGuard;

$guard = new SessionGuard($session, $userProvider);

// Login (regenerates session ID to prevent fixation)
$guard->login($user);

// Authenticate from session
$user = $guard->authenticate($request);

// Logout
$guard->logout();
```

### WebAuthn / Passkey Guard

[](#webauthn--passkey-guard)

Integrates with [MonkeysLegion-WebAuthn](https://github.com/MonkeysCloud/MonkeysLegion-WebAuthn) for passwordless authentication:

```
use MonkeysLegion\Auth\Guard\WebAuthnGuard;
use MonkeysLegion\Auth\Event\PasskeyAuthenticated;
use MonkeysLegion\Auth\Attribute\Passkey;

// 1. Register the guard
$manager->register('webauthn', new WebAuthnGuard($userProvider));

// 2. In your controller: verify the assertion, then set the request attribute
$credential = $webAuthnService->verifyAuthentication($assertionResponse);
$request = $request->withAttribute('webauthn.user_handle', $credential->userHandle);

// 3. The guard resolves the user from the verified attribute
$user = $manager->guard('webauthn')->authenticate($request);

// 4. Dispatch audit event
$dispatcher->dispatch(new PasskeyAuthenticated(
    userId: $user->getAuthIdentifier(),
    credentialId: base64_encode($credential->credentialId),
    ipAddress: $serverParams['REMOTE_ADDR'] ?? null,
));
```

Mark routes/controllers as requiring passkey authentication:

```
#[Passkey]                                      // userVerification: 'preferred'
#[Passkey(userVerification: 'required')]        // high-assurance actions
public function transferFunds(): Response { ... }
```

### Attribute-Based Security

[](#attribute-based-security)

```
use MonkeysLegion\Auth\Attribute\Authenticated;
use MonkeysLegion\Auth\Attribute\RequiresRole;
use MonkeysLegion\Auth\Attribute\RequiresPermission;
use MonkeysLegion\Auth\Attribute\RateLimit;

#[Authenticated(guard: 'jwt')]
#[RequiresRole(['admin', 'editor'], mode: 'any')]
#[RateLimit(maxAttempts: 60, decaySeconds: 60)]
class ArticleController
{
    #[RequiresPermission('articles.publish')]
    public function publish(int $id): Response
    {
        // Only authenticated users with admin/editor role
        // and articles.publish permission can reach here
    }
}
```

### Policy Gate

[](#policy-gate)

```
use MonkeysLegion\Auth\Policy\Gate;

$gate = new Gate();
$gate->define('update-post', fn($user, $post) => $user->id === $post->authorId);

// Check
$gate->allows($user, 'update-post', $post);    // true/false
$gate->authorize($user, 'update-post', $post);  // throws UnauthorizedException

// Detailed deny reason
$result = $gate->inspect($user, 'update-post', $post);
$result->allowed;  // false
$result->reason;   // "Not authorized for: update-post"
```

### Password Hashing with Policy

[](#password-hashing-with-policy)

```
use MonkeysLegion\Auth\Service\PasswordHasher;
use MonkeysLegion\Auth\DTO\PasswordPolicy;

$hasher = new PasswordHasher(
    policy: new PasswordPolicy(
        minLength: 12,
        requireUppercase: true,
        requireNumbers: true,
        requireSymbols: true,
        rejectCommon: true,
    ),
);

$hash = $hasher->hash('MyStr0ng!Pass');
$hasher->verify('MyStr0ng!Pass', $hash); // true
$hasher->needsRehash($hash);             // false
```

Security Features
-----------------

[](#security-features)

- **Token family tracking** — detects refresh token reuse attacks
- **CSPRNG token IDs** — `random_bytes(16)` for all token identifiers
- **Session fixation prevention** — session regenerated on every login
- **Token versioning** — increment version to invalidate all sessions/tokens globally
- **Timing-safe comparisons** — `hash_equals` for all credential/token checks
- **Account lockout** — configurable failed attempt limits
- **Audit trail** — all auth events include correlation IDs

Testing
-------

[](#testing)

```
composer test
# 122 tests, 277 assertions
```

License
-------

[](#license)

MIT © [MonkeysCloud](https://monkeys.cloud)

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance98

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 93.6% 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 ~33 days

Total

11

Last Release

11d ago

Major Versions

1.0.3 → 2.0.x-dev2025-12-08

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2913369?v=4)[Jorge Peraza](/maintainers/yorchperaza)[@yorchperaza](https://github.com/yorchperaza)

---

Top Contributors

[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (44 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (3 commits)")

---

Tags

authauthenticationjwtphpphp-library

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-auth/health.svg)

```
[![Health](https://phpackages.com/badges/monkeyscloud-monkeyslegion-auth/health.svg)](https://phpackages.com/packages/monkeyscloud-monkeyslegion-auth)
```

###  Alternatives

[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.1k](/packages/typo3-cms-core)[spiral/framework

Spiral, High-Performance PHP/Go Framework

2.1k2.2M66](/packages/spiral-framework)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)[windwalker/framework

The next generation PHP framework.

25740.3k1](/packages/windwalker-framework)

PHPackages © 2026

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