PHPackages                             sirix/mezzio-authentication - 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. sirix/mezzio-authentication

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

sirix/mezzio-authentication
===========================

Token-based authentication package for Mezzio framework with optional attribute-based support

1.0.0(1mo ago)0434MITPHPPHP ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since May 11Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/sirix777/mezzio-authentication)[ Packagist](https://packagist.org/packages/sirix/mezzio-authentication)[ Fund](https://buymeacoffee.com/sirix)[ GitHub Sponsors](https://github.com/sirix777)[ RSS](/packages/sirix-mezzio-authentication/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (2)Dependencies (23)Versions (4)Used By (0)

Mezzio Authentication
=====================

[](#mezzio-authentication)

Token-based authentication package for Mezzio framework with optional attribute support.

Stability
---------

[](#stability)

The `1.x` line treats the public contracts, middleware behavior, and request attribute names documented below as stable integration points.

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

[](#installation)

```
composer require sirix/mezzio-authentication
```

Package is auto-registered via `extra.laminas.config-provider`.

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

[](#quick-start)

### 1. Configuration

[](#1-configuration)

Add to `config/autoload/authentication.global.php`:

```
return [
    'authentication' => [
        'default_storage' => 'session',
        'transport' => [
            'driver' => 'bearer',
            'storage' => 'session',
        ],
        'session' => [
            'prefix' => '_authentication.tokens.',
        ],
        'storages' => [
            // optional named storage mapping:  =>
            // 'redis' => App\Authentication\Storage\RedisTokenStorage::class,
        ],
        'cookie' => [
            'name' => 'mezzio_authentication',
            'path' => '/',
            'domain' => null,
            'secure' => false,
            'http_only' => true,
            'same_site' => 'Lax',
        ],
        'actor' => [
            'roles_key' => 'roles',
            'role_key' => 'role',
        ],
    ],
];
```

### 2. Session Setup (for SessionTokenStorage)

[](#2-session-setup-for-sessiontokenstorage)

```
composer require mezzio/mezzio-session
```

Register `Mezzio\Session\SessionMiddleware` in your pipeline **before** authentication middleware.

Also configure a session persistence adapter for your application (for example cookie-based or cache-backed persistence), per `mezzio/mezzio-session` documentation.

If `mezzio/mezzio-session` is not installed, `SessionTokenStorage` is not wired and the package uses `NullTokenStorage` as fallback.

If a token id is provided by transport but current storage backend is unavailable for that request (for example missing session in request), authentication middleware treats request as guest instead of failing with a storage runtime exception.

### 3. Protect Routes

[](#3-protect-routes)

**Manual middleware registration:**

```
use Sirix\Mezzio\Authentication\Middleware\AuthenticateMiddleware;

$app->get('/api/me', [
    AuthenticateMiddleware::class,
    ProfileHandler::class,
], 'profile');
```

**With `sirix/mezzio-routing-attributes` (optional):**

```
composer require "sirix/mezzio-routing-attributes:^1.0"
```

```
use Sirix\Mezzio\Authentication\Attribute\Authenticated;
use Sirix\Mezzio\Routing\Attributes\Attribute\Get;

#[Get('/api/me', name: 'profile')]
#[Authenticated]
final class ProfileHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // User is authenticated
    }
}
```

Core Concepts
-------------

[](#core-concepts)

### AuthManager

[](#authmanager)

Main HTTP-facing entry point for authentication operations. Current request authentication state is read from the provided `ServerRequestInterface`; it is not stored in a mutable singleton service.

```
use Sirix\Mezzio\Authentication\Contract\AuthManagerInterface;

$manager->login(['userId' => 1, 'roles' => ['admin']]);
$manager->context($request); // AuthContextInterface from request attributes
$manager->check($request);  // true/false based on request auth context
$manager->guest($request);  // true/false based on request auth context
$manager->actor($request);  // ActorInterface from request auth context
$manager->token($request);  // TokenInterface from request auth context
$response = $manager->logout($request, $response); // detaches token from transport
```

For HTTP handlers and middleware, prefer `AuthManagerInterface::actor($request)` or the documented request attributes. Do not resolve a "current user" singleton from the container for per-request authorization.

### Token Storage

[](#token-storage)

Two built-in storage backends:

- `NullTokenStorage` — tokens are generated but not persisted (testing/stateless).
- `SessionTokenStorage` — tokens stored in session via `mezzio/mezzio-session`.

When `mezzio/mezzio-session` is unavailable, only `NullTokenStorage` is active.

Custom storage implements `TokenStorageInterface`.

### Token Transport

[](#token-transport)

Extracts token ID from requests:

- `BearerTokenTransport` — `Authorization: Bearer ` header.
- `CookieTokenTransport` — cookie-based transport.

Custom transport implements `TokenTransportInterface`.

### Actors

[](#actors)

Actors represent the authenticated user:

```
use Sirix\Mezzio\Authentication\Contract\ActorInterface;

$actor->getRoles(); // ['admin', 'editor']
```

- `PayloadActorProvider` — extracts roles from token payload.
- `ContextActorProvider` — resolves actor from authentication context.
- `GuestActor` — default guest actor with role `guest`.

`SecurityActorProviderInterface` is intended for non-request or application-managed security contexts. Its default `ContextActorProvider` reads from the injected `AuthContextInterface` service and is not automatically synchronized with the current HTTP request. It is not a replacement for `AuthManagerInterface::actor($request)` in HTTP code.

### Middleware

[](#middleware)

MiddlewareBehavior`AuthenticateMiddleware`Requires authentication, throws `Exception\AuthenticationException` (401)`OptionalAuthenticateMiddleware`Attempts authentication, passes through regardless`GuestOnlyMiddleware`Allows only guests, throws `Exception\AlreadyAuthenticatedException` (403)### Attributes

[](#attributes)

AttributeMiddleware Added`#[Authenticated]``AuthenticateMiddleware``#[GuestOnly]``OptionalAuthenticateMiddleware` + `GuestOnlyMiddleware`When `sirix/mezzio-routing-attributes` is installed, attributes auto-inject middleware. Without it, middleware must be registered manually.

Request Attributes
------------------

[](#request-attributes)

After `AuthenticateMiddleware` or `OptionalAuthenticateMiddleware` processes a request, these stable attributes are available:

```
use Sirix\Mezzio\Authentication\AuthenticationAttributes;

$context = $request->getAttribute(AuthenticationAttributes::Context->value);
$token   = $request->getAttribute(AuthenticationAttributes::Token->value);
$actor   = $request->getAttribute(AuthenticationAttributes::Actor->value);
```

Stable attribute names:

```
'sirix.authentication.context'
'sirix.authentication.token'
'sirix.authentication.actor'
```

These attributes are the package's current-request state boundary and are safe for long-running workers because they live on the PSR-7 request instance.

### RBAC Integration

[](#rbac-integration)

`sirix/mezzio-rbac` can authorize the current request by reading the actor from:

```
'sirix.authentication.actor'
```

The authentication package does not depend on RBAC. The integration contract is structural: the actor exposes `getRoles(): array`.

`SessionTokenStorage` reads session from request attributes in this order:

1. `Mezzio\Session\SessionInterface::class`
2. `'session'`

When using session storage, `Mezzio\Session\SessionMiddleware` must run before authentication middleware.

For cookie transport in production, use `secure: true` over HTTPS, keep `http_only: true`, and choose a `same_site` policy appropriate for your application flow.

Extensibility
-------------

[](#extensibility)

### Custom Actor Provider

[](#custom-actor-provider)

```
use Sirix\Mezzio\Authentication\Contract\AuthActorProviderInterface;
use Sirix\Mezzio\Authentication\Contract\ActorInterface;
use Sirix\Mezzio\Authentication\Contract\TokenInterface;

final readonly class MyActorProvider implements AuthActorProviderInterface
{
    public function getActor(TokenInterface $token): ?ActorInterface
    {
        // Custom logic to resolve actor from token
    }
}
```

Register in your dependencies:

```
'dependencies' => [
    'factories' => [
        AuthActorProviderInterface::class => MyActorProviderFactory::class,
    ],
],
```

### Custom Token Storage

[](#custom-token-storage)

```
use Sirix\Mezzio\Authentication\Contract\TokenStorageInterface;

final readonly class RedisTokenStorage implements TokenStorageInterface
{
    // implement create(), load(), delete()
}
```

### Custom Transport

[](#custom-transport)

```
use Sirix\Mezzio\Authentication\Contract\TokenTransportInterface;

final readonly class QueryParamTransport implements TokenTransportInterface
{
    // implement fetch(), attach(), detach()
}
```

Exceptions
----------

[](#exceptions)

ExceptionPurpose`Exception\AuthenticationException`401 Unauthorized response`Exception\AlreadyAuthenticatedException`403 Forbidden response`Exception\StorageException`Token storage failure`Sirix\ContainerResolver\Exception\MissingContainerServiceException`Required container service is not registered while a factory builds an object`Sirix\ContainerResolver\Exception\InvalidContainerServiceException`Container service has an unexpected type`Sirix\ContainerResolver\Exception\InvalidConfigValueException`Factory configuration value has an unexpected type or unsupported valueHTTP exceptions provide `getStatusCode()`, `getHeaders()`, and `getPublicMessage()` for integration with error handling middleware. Factory configuration errors are reported by `sirix/container-resolver` exceptions.

Design Notes
------------

[](#design-notes)

The package depends on contracts, not on concrete persistence. Built-in implementations cover common use cases, but everything is replaceable via PSR-11 service configuration.

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance90

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

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 ~11 days

Total

3

Last Release

53d ago

Major Versions

0.1.0 → 1.x-dev2026-06-02

### Community

Maintainers

![](https://www.gravatar.com/avatar/6ecccf9003c061847e877eeea3bdf1b382f6f9dbb11d33112d6b2740bf0533f9?d=identicon)[sirix777](/maintainers/sirix777)

---

Top Contributors

[![sirix777](https://avatars.githubusercontent.com/u/68593154?v=4)](https://github.com/sirix777 "sirix777 (1 commits)")

---

Tags

middlewarelaminasauthAuthenticationtokenpsr-15mezzioattributes

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sirix-mezzio-authentication/health.svg)

```
[![Health](https://phpackages.com/badges/sirix-mezzio-authentication/health.svg)](https://phpackages.com/packages/sirix-mezzio-authentication)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k19.5M1.8k](/packages/cakephp-cakephp)[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)[mezzio/mezzio

PSR-15 Middleware Microframework

3923.8M126](/packages/mezzio-mezzio)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k16](/packages/tempest-framework)[sunrise/http-router

A powerful solution as the foundation of your project.

17451.8k11](/packages/sunrise-http-router)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.2k](/packages/typo3-cms-core)

PHPackages © 2026

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