PHPackages                             marcelbonnet/slim-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. marcelbonnet/slim-auth

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

marcelbonnet/slim-auth
======================

Authorization and authentication for the Slim Framework using ZF2 Authentication and Acl components

2.0.0(9y ago)1187MITPHP &gt;=5.6.0

Since Jun 24Compare

[ Source](https://github.com/marcelbonnet/slim-auth)[ Packagist](https://packagist.org/packages/marcelbonnet/slim-auth)[ Docs](https://github.com/marcelbonnet/slim-auth)[ RSS](/packages/marcelbonnet-slim-auth/feed)WikiDiscussions Synced today

READMEChangelogDependencies (9)Versions (13)Used By (0)

Slim Framework Authentication and Authorization Middleware
==========================================================

[](#slim-framework-authentication-and-authorization-middleware)

This project uses parts of Zend Framework, like Zend Auth classes, Zend ACL and Zend config.

My goal was to build a reusable Middleware to authenticate through LDAP and/or RDBMS.

Install
=======

[](#install)

```
$ composer require marcelbonnet/slim-auth
```

Bundled Mechanism
=================

[](#bundled-mechanism)

- Authentication through LDAP (see sample config for LDAP and AD)
- Authentication through RDBMS
- Authorization based on user roles kept in a RDBMS' table.

RDBMS Mechanism
---------------

[](#rdbms-mechanism)

Agnostic table design. The only thing slim-auth needs to know is where users and roles are stored , using an instance of Doctrine ORM's EntityManager.

Requirements
============

[](#requirements)

- Slim Framework v. 3.x
- PHP &gt;= 5.6
- Doctrine ORM &gt;= 2.5

To see all dependencies:

How To (slim-auth min version 2.0.0)
====================================

[](#how-to-slim-auth-min-version-200)

1.x not compatible.

Dao
---

[](#dao)

This package suppose you have a User `0..+` Role(s). Here an example design (use whatever attribute names you want):

```
class User {

    protected $username;
    protected $passwordHash;
    /**
    @OneToMany(targetEntity="Role", ...)
    */
    protected $roles;
}

class Role {
    /**
    The role name
    @var string
    */
    protected $role;
    /**
    @ManyToOne(targetEntity="User")
    */
    protected $user;
}
```

index.php
---------

[](#indexphp)

```
use marcelbonnet\Slim\Auth\ServiceProvider\SlimAuthProvider;
use Zend\Authentication\Storage\Session as SessionStorage;
use marcelbonnet\Slim\Auth\Middleware\Authorization;
use marcelbonnet\Slim\Auth\Handlers\RedirectHandler;
use marcelbonnet\Slim\Auth\Adapter\LdapRdbmsAdapter;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\Http\Request as SlimHttpRequest;
use \Slim\Http\Response as SlimHttpResponse;

require_once 'vendor/autoload.php';

/* ****************************************************************************
 * Slim App and Config
 * ****************************************************************************
 */
$config = require '../conf/config.php';
$app = new \Slim\App($config);

// Fetch DI Container
$container = $app->getContainer();

/* ****************************************************************************
 * Authentication/Authorization
 * ****************************************************************************
 */
$acl = new Acl();
//ACLed Slim Route
$container['router'] = new \marcelbonnet\Slim\Auth\Route\AuthorizableRouter(null, $acl);
$container['acl']    = $acl;

$adapterOptions = [];
//if you want auth to be valid if some column exists with an expected value:
// $adapterOptions = [
//              'checkUserIsActivated'  => 'my_column_in_user_table',
//              'userIsActivatedFlag'       => true
//      ];
$adapter = new marcelbonnet\Slim\Auth\Adapter\LdapRdbmsAdapter(
        '/some/file.conf',  //LDAP config or NULL if not using LDAP
        $myEntityManager, //an Doctrine's Entity Manager instance
        "\Your\Project\Dao\Role",    //Role class
        "role", //Role's class role attribute
        "user", //Role's class user attribute (the @ManyToOne attrib)
        "\Your\Project\Dao\User", //User class
        "username", //User name attribute
        "passwordHash", //password (as a hash) attribute
        marcelbonnet\Slim\Auth\Adapter\LdapRdbmsAdapter::AUTHENTICATE_RDBMS, //auth method: LdapRdbmsAdapter::AUTHENTICATE_RDBMS | LdapRdbmsAdapter::AUTHENTICATE_LDAP
        10, //a hash factor
        PASSWORD_DEFAULT, //hash algorithm
        $adapterOptions //if needed
        );

$container["authAdapter"] = $adapter;

$slimAuthProvider = new SlimAuthProvider();
$slimAuthProvider->register($container);

$app->add(new Authorization( $container["auth"], $acl, new RedirectHandler("auth/notAuthenticated", "auth/notAuthorized") ));
# checks:
#$username=(is_array(@$c["auth"]->getStorage()->read()))? @$c["auth"]->getStorage()->read()["username"] : @$c["auth"]->getStorage()->read();
#$userRoles=(is_array(@$c["auth"]->getStorage()->read()))? @$c["auth"]->getStorage()->read()["role"] : array();

/**
    Example Routes: you must set allowed Roles (as one string or as an array or string roles) for each route.
*/
$app->get('/', 'My\Controller:home' )->setName("home")->allow(Acl::MEMBER);

$app->get('/home', function (SlimHttpRequest $request, SlimHttpResponse $response, $args) use($container) {
    $container->get('router')->getNamedRoute('home')->run($request, $response);
})->allow(Acl::MEMBER);

$app->get('/hello[/{name}]', 'My\Controller:sayHello')->setName('hello')->allow([Acl::GUEST, Acl::MEMBER]);
$app->get('/protected', 'My\Controller:callProtectedResource')->setName('protected')->allow(Acl::ADMIN);

$app->run();
```

Now your ACL class should look like:

```
class Acl extends SlimAuthAcl
{
    const GUEST                     = "guest";
    const ADMIN                     = "admin";
    const MEMBER                    = "member";

    public function __construct()
    {
        // APPLICATION ROLES
        $this->addRole(self::GUEST);

        $this->addRole(self::MEMBER, self::GUEST);

        /* **************************************
         * WARNING: ALLOW ALL:
         * **************************************
         */
        $this->addRole(self::ADMIN);
        $this->allow(self::ADMIN);
    }

}
```

How it looks in MySQL
---------------------

[](#how-it-looks-in-mysql)

```
mysql> SELECT * FROM core__users;
+----+--------------+--------------------------------------------------------------+
| id | username     | passwordHash                                                 |
+----+--------------+--------------------------------------------------------------+
|  2 | marcelbonnet | $2y$15$9b9Vb5K/Rcg.s6Gjn0cpnu4iAhRdbWA0lIxqzf5mLl81WW.qYtXzK |
+----+--------------+--------------------------------------------------------------+

mysql> SELECT * FROM core__user_roles;
+----+------------+--------+
| id | fk_user_id | role   |
+----+------------+--------+
|  5 |          2 | admin  |
|  3 |          2 | member |
+----+------------+--------+
```

History
-------

[](#history)

This project started as a modified version of a development branch from jeremykendall/slim-auth.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity65

Established project with proven stability

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

Recently: every ~18 days

Total

12

Last Release

3581d ago

Major Versions

0.0.5 → 1.0.02016-06-26

1.0.5 → 2.0.02016-09-10

PHP version history (2 changes)0.0.1PHP &gt;=5.5.0

0.0.2PHP &gt;=5.6.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/15176769?v=4)[Marcel Bonnet](/maintainers/marcelbonnet)[@marcelbonnet](https://github.com/marcelbonnet)

---

Tags

authAuthenticationslimzendauthorizationzf2Zend Frameworkslim-framework

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/marcelbonnet-slim-auth/health.svg)

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

###  Alternatives

[jeremykendall/slim-auth

Authorization and authentication for the Slim Framework using ZF2 Authentication and Acl components

24324.7k1](/packages/jeremykendall-slim-auth)[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.7k143.0M274](/packages/league-oauth2-server)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

40921.3M85](/packages/auth0-auth0-php)[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2745.2M3](/packages/auth0-login)[dyorg/slim-token-authentication

Slim 3.0+ Token Authentication Middleware

76109.8k](/packages/dyorg-slim-token-authentication)[potievdev/slim-rbac

Role Based Access Control middleware for Slim 3

345.5k1](/packages/potievdev-slim-rbac)

PHPackages © 2026

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