PHPackages                             marcel-maqsood/session-auth-middleware - 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. [Framework](/categories/framework)
4. /
5. marcel-maqsood/session-auth-middleware

ActiveLibrary[Framework](/categories/framework)

marcel-maqsood/session-auth-middleware
======================================

The SessionAuthMiddleware is a PSR-15 middleware that provides handling for sessions and logins in a Laminas/Mezzio application

v1.360(2mo ago)0164MITPHP

Since May 2Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/marcel-maqsood/Mezzio-Session-Auth-Middleware)[ Packagist](https://packagist.org/packages/marcel-maqsood/session-auth-middleware)[ Docs](https://github.com/marcel-maqsood/Mezzio-Session-Auth-Middleware)[ RSS](/packages/marcel-maqsood-session-auth-middleware/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (22)Versions (61)Used By (0)

Session-Auth-Middleware
=======================

[](#session-auth-middleware)

You can install this package with the following command: `composer require marcel-maqsood/session-auth-middleware`

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

[](#configuration)

### Additional Notes:

[](#additional-notes)

As our Middleware can run on any request, it is meant to be injected within your applications `config\autoload\dependencies.global.php` file, as seen in `dependencies.global.php`:

```
'dependencies' =>
[
    'aliases' =>
    [
        AuthenticationInterface::class => PhpSession::class,
        UserRepositoryInterface::class => PDORepository::class,
    ],
    'invokables' => [],
    'factories' =>
    [
        PersistentPDO::class => PersistentPDOFactory::class,
        PDORepository::class => PDORepositoryFactory::class,
        Mezzio\Session\SessionMiddleware::class => Mezzio\Session\SessionMiddlewareFactory::class
    ],
],

```

This fullfils multiple purposes:

- You dont have to configure each ConfigProvide within your modules
- Any request will always be capabale of SessionAuth Handling (But this will only be used if the route contains our SessionAuthMiddleware)
- You cant forget to add our base config in every new module that you supply; which could be a hustle otherwise.

You can find our default configuration in `config\autoload\authentication.global.php` and drop it into your applications `config\autoload\` folder. It contains every configuration needed to run our SessionAuthMiddleware and can easily be copied and adjusted..

Also, you have to add the `Mezzio\Session\SessionMiddleware` to your pipeline (`config\pipeline.php`), it must be included in the very top of the Pipeline:

```
$app->pipe(ErrorHandler::class);
$app->pipe(ServerUrlMiddleware::class);
$app->pipe(SessionMiddleware::class); //  'username', //- The key in which the username is within $_POST. default: 'username'
    'password' => 'password', //- The key in which the password is within $_POST. default: 'password'
    'repository' => [ //- An array, in which the details for our database-table are.
        'table' => 'login', //- The table, in which we look for the user.  default: 'logins'
        'fields' => [ //- An array in which the fields of that table are to authenticate a user.
            'identities' => [ //An array with all fields that contains login-names or mails, and so on.
                'username',
                'email'
            ],
            'password' => 'anyPass' //- The key, with which we check if the password in $_POST is equal.
        ],
        'table_override' => [ // - An array, in which we define routes and their database-table prefix that the system will use tot check if they start with the key of any entry.
            'user'  => 'user', // Routename starts with 'user' => use table prefix 'user' : user - for base table, user_permissions for all permissions that only user-groups can have, etc.
            'admin' => 'admin',
        ],
    ],
    'security' => [ //- An array for our security features.
        'algo' => 'sha256', //- The algorithm used for generating the SessionHash stored in the database. default: 'sha256'
        'salt' => 'anySalt', // - The string which we use to harden our hashes be appending it.
        'fields' => [ //- An array, in which we define session related fields within our 'logins' table to be used to check if the session is valid.
            'session' => 'sessionhash', //- The key which we use to get the users current session-hash and check if it matches the request. default: 'sessionhash'
            'stamp' => 'sessionstart' //- The key which we use to get the session-start of the current session to check if it is still valid. default: 'sessionstart'
        ]
    ]
]

```

if the key `'table_override'` is not set within `'repository'`, the system will only use the `'table'` value set in `'repository'` to map to a table.

Our SessionAuthMiddleware also requires this config entry:

```
'session' => [
    'config' => [
        'cookie_lifetime' => 60 * 60 * 1, //- Time in seconds which the cookie is valid. default: '1h'
        'gc_lifetime' => 60 * 60 * 24 //- Time in seconds which the created session is valid. default: '24h'
    ]
]

```

##### Permission Management

[](#permission-management)

As this is a authentication handler, we also want to check if a user has the permission to see its requested content.

- Check if the request's user has permissions on the current route.
- Redirecting towards the referring page, if the user does not have permissions to see its requested content.
- Redirecting towards login-forms if the user directly requested a page without permission and without beeing on the page before.
- Redirecting from login-form towards a page if the user has permissions to that page.
- Permissions can be marked as "allowBypass" which grants the user the same right as having the permission, like for routes that should always be accessabile but defined to use as fallback.
- Definition of a fallback permission (route) if the user does not have permission on its current route and should be redirected towards another route.
- You can define permissions with value "\*" (asteriks) to grant a group all permissions.

Default table definition within any global or local config.php (located in `config\autoload\`):

```
return [
    'tables' => [
        'user' => [
            'tableName' => 'users',
            'identifier' => 'loginId',
            'loginName' => 'username',
            'display' = 'hidden',
            'resetHash' => 'forgothash',
            'resetValid' => 'forgotvalid'
        ],
        'user_group_relation' => [
            'tableName' => 'user_has_groups',
            'identifier' => 'lhgId',
            'group_identifier' => 'groupId',
            'login_identifier' => 'loginId',
        ],
        'user_groups' => [
            'tableName' => 'user_groups',
            'identifier' => 'groupId',
            'name' => 'name',
            'display' = 'hidden'
        ],
        'user_permissions' => [
            'tableName' => 'user_permissions',
            'identifier' => 'permissionId',
            'name' => 'name',
            'value' => 'value',
            'noPermFallback' => 'noPermFallback',
            'allowBypass' => 'allowBypass',
            'display' = 'hidden'
        ],
        'user_group_permission_relation' => [
            'tableName' => 'user_group_has_permissions',
            'identifier' => 'ghpId',
            'permission_identifier' => 'permissionId',
            'group_identifier' => 'groupId',
        ],
    ]
]

```

As stated before, you can define permission fallbacks if a given permission is not granted and should redirect towards somewhere else.

Permissions cannot be granted to certain users but instead to a group which can be granted to users. users may have as much groups as you want and groups may have as much permissions as you want.

#### Password Reset Functionality

[](#password-reset-functionality)

As your application might need a reset-password function, we included a basic Handler within `Handler\ForgotPasswordHandler`It uses basic form posts with the follwing needed input-fields:

- username (which is used to find a user account with the value as its username or email)
- password
- action; either "submit" or "request" so that the handler know what he should do.

The password reset Handler sends an Email to the user (if existing) with a link towards its designated password change form. This is a basic "request" reset-password form:

```

	div class="row mb-2">

			Reset Password

			Back to Login

```

It should be included in your "login.html.twig"

```
	{{ include('@app/ForgotPassword.html.twig') }}

```

and uses the variable "resetDestination" to send the password-reset request towards the correct handler, as defined by your config:

```
'loginHandling'  => [
    'adminLogin' => [
        'name'             => 'Admin',
        'destination'      => 'adminLanding',
        'resetDestination' => 'adminPasswordReset',
    ],
]

```

KEEP IN MIND: This is still on your LoginRoute and as such, requests towards the PasswordResetHandler need to be directed directly towards it.

After the user submitted its password-reset request; He recieves an email with a link towards our PasswordResetHandler, including the queryParam "hash", which was saved in the user account after submitting the request. We also saved the validUntil date of that hash as it has to expire at some point; by default config, we use 30 days.

a basic password-submit form should look like this:

```

			Update

			    Your password was changed. You will receive an email.

			    Your password couldn't be changed.

```

As our HTML-Templates use some javascript, we included you all the functions that might be handy; you find the js in `js\basic.js` it is based on JQuery so be sure to included JQuery in your project.

##### Error Messages

[](#error-messages)

Our Session-Auth-Middleware will store a cookie that is valid for 60 seconds if it encounters any issues:

```
setcookie("error", $this->errorMessage, time() + 60, '/');

```

You can use that cookie to receive the error message and display it to the user.

Credits
-------

[](#credits)

This Software has been developed by MazeDEV/Marcel-Maqsood().

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance85

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

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

Recently: every ~41 days

Total

60

Last Release

76d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cb3e80af811448d9ddd7cc2147e8f6de321c14dd718db4108fec610c284f490e?d=identicon)[MazeDEV\_DE](/maintainers/MazeDEV_DE)

---

Top Contributors

[![marcel-maqsood](https://avatars.githubusercontent.com/u/46565549?v=4)](https://github.com/marcel-maqsood "marcel-maqsood (4 commits)")

---

Tags

middlewareframeworkAuthenticationsessionMazeDEV

### Embed Badge

![Health badge](/badges/marcel-maqsood-session-auth-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/marcel-maqsood-session-auth-middleware/health.svg)](https://phpackages.com/packages/marcel-maqsood-session-auth-middleware)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[cakephp/authentication

Authentication plugin for CakePHP

1153.6M67](/packages/cakephp-authentication)[htmlburger/wpemerge

A micro framework which modernizes WordPress as a CMS development by providing tools to implement MVC and more.

456137.8k8](/packages/htmlburger-wpemerge)[mezzio/mezzio-authentication-oauth2

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

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[igniphp/framework

Swoole, PSR-7, PSR-15 modular micro anti-framework.

2651.0k1](/packages/igniphp-framework)

PHPackages © 2026

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