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

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

jeremykendall/slim-auth
=======================

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

1.0.1(10y ago)24324.7k↓81.3%36[12 issues](https://github.com/jeremykendall/slim-auth/issues)[2 PRs](https://github.com/jeremykendall/slim-auth/pulls)1MITPHPPHP &gt;=5.3.7CI failing

Since Dec 15Pushed 8y ago24 watchersCompare

[ Source](https://github.com/jeremykendall/slim-auth)[ Packagist](https://packagist.org/packages/jeremykendall/slim-auth)[ Docs](https://github.com/jeremykendall/slim-auth)[ RSS](/packages/jeremykendall-slim-auth/feed)WikiDiscussions develop Synced 3w ago

READMEChangelog (10)Dependencies (8)Versions (15)Used By (1)

Slim Auth [![Build Status](https://camo.githubusercontent.com/7da91a6d9bdcc13e7ffdef86d483373249e9b59a74e28eb75ebd0b8d87e070cd/68747470733a2f2f7472617669732d63692e6f72672f6a6572656d796b656e64616c6c2f736c696d2d617574682e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/jeremykendall/slim-auth) [![Coverage Status](https://camo.githubusercontent.com/8348f8c3744652dffdff54c75f35db8d6a4a3282db5bbee06a33223bbcce0bed/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6a6572656d796b656e64616c6c2f736c696d2d617574682f62616467652e706e673f6272616e63683d6d6173746572)](https://coveralls.io/r/jeremykendall/slim-auth?branch=master) [![Dependencies Status](https://camo.githubusercontent.com/1ef5fa3b4782b21bdd45322af787e57dfd3e6022e4f89e49a530282621377434/68747470733a2f2f646570656e64696e672e696e2f6a6572656d796b656e64616c6c2f736c696d2d617574682e706e67)](http://depending.in/jeremykendall/slim-auth)
=======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#slim-auth---)

Slim Auth is an authorization and authentication library for the [Slim Framework](http://slimframework.com/). Authentication is provided by the Zend Framework [Zend\\Authentication](http://framework.zend.com/manual/current/en/modules/zend.authentication.intro.html)component, and authorization by the Zend Framework [Zend\\Permissions\\Acl](http://framework.zend.com/manual/current/en/modules/zend.permissions.acl.intro.html) component.

Fair Warning: Documentation Mostly Complete
-------------------------------------------

[](#fair-warning-documentation-mostly-complete)

Slim Auth is fully functional and production ready (I've used it in production in multiple projects), but this documentation is incomplete. (Current status of the documentation is ~90% complete.)

If you're familiar with [Zend\\Authentication](http://framework.zend.com/manual/current/en/modules/zend.authentication.intro.html) and [Zend\\Permissions\\Acl](http://framework.zend.com/manual/current/en/modules/zend.permissions.acl.intro.html), you'll be able to implement the library without any trouble. Otherwise, you might want to wait for the docs to be completed (no ETA) or open a GitHub issue with any questions or problems you encounter.

Caveat emptor and all that.

Slim SessionCookie No Longer Recomended
---------------------------------------

[](#slim-sessioncookie-no-longer-recomended)

**TL;DR**: You *will* experience unexpected behavior if you use `Zend\Authentication\Storage\Session` as your auth storage and `Slim\Middleware\SessionCookie` to provide encrypted cookies when your Slim version is &gt;= 2.6.

Earlier versions of this documentation (and the [sample implementation](https://github.com/jeremykendall/slim-auth-impl)) demonstrated the use of Slim's [SessionCookie Middleware](http://docs.slimframework.com/#Cookie-Session-Store) as a way to handle session storage in concert with Zend Session. As of [Slim 2.6.0](https://github.com/slimphp/Slim/releases/tag/2.6.0), Zend Session and Slim's SessionCookie middleware no longer play well together, and I've opted for a Zend Session only approach.

Requirements
------------

[](#requirements)

Slim Auth works with all versions of Slim 2 &gt;= 2.4.2. Slim Auth has not been tested against the upcoming Slim 3 release.

Example Implementation
----------------------

[](#example-implementation)

I've put together an example implementation to demonstrate the library in action. The example implementation can be found [here](https://github.com/jeremykendall/slim-auth-impl).

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

[](#installation)

Installation is provided via [Composer](http://getcomposer.org).

First, install Composer.

```
curl -s https://getcomposer.org/installer | php

```

Then install Slim Auth with the following Composer command.

```
composer require jeremykendall/slim-auth

```

Finally, add this line at the top of your application’s index.php file:

```
require 'vendor/autoload.php';

```

Preparing Your App For Slim Auth
--------------------------------

[](#preparing-your-app-for-slim-auth)

### Database

[](#database)

Your database should have a user table, and that table must have a `role`column. The contents of the `role` column should be a string and correspond to the roles in your ACL. The table name and all other column names are up to you.

Here's an example schema for a user table. If you don't already have a user table, feel free to use this one:

```
CREATE TABLE IF NOT EXISTS [users] (
    [id] INTEGER NOT NULL PRIMARY KEY,
    [username] VARCHAR(50) NOT NULL,
    [role] VARCHAR(50) NOT NULL,
    [password] VARCHAR(255) NULL
);

```

### ACL

[](#acl)

An Access Control List, or ACL, defines the set of rules that determines which group of users have access to which routes within your Slim application. Below is a very simple example ACL. Please pay special attention to the comments.

*Please refer to the [Zend\\Permissions\\Acl documentation](http://framework.zend.com/manual/current/en/modules/zend.permissions.acl.intro.html) for complete details on using the Zend Framework ACL component.*

```
namespace Example;

use Zend\Permissions\Acl\Acl as ZendAcl;

class Acl extends ZendAcl
{
    public function __construct()
    {
        // APPLICATION ROLES
        $this->addRole('guest');
        // member role "extends" guest, meaning the member role will get all of
        // the guest role permissions by default
        $this->addRole('member', 'guest');
        $this->addRole('admin');

        // APPLICATION RESOURCES
        // Application resources == Slim route patterns
        $this->addResource('/');
        $this->addResource('/login');
        $this->addResource('/logout');
        $this->addResource('/member');
        $this->addResource('/admin');

        // APPLICATION PERMISSIONS
        // Now we allow or deny a role's access to resources. The third argument
        // is 'privilege'. We're using HTTP method as 'privilege'.
        $this->allow('guest', '/', 'GET');
        $this->allow('guest', '/login', array('GET', 'POST'));
        $this->allow('guest', '/logout', 'GET');

        $this->allow('member', '/member', 'GET');

        // This allows admin access to everything
        $this->allow('admin');
    }
}

```

#### The Guest Role

[](#the-guest-role)

Please note the `guest` role. **You must use the name** `guest` **as the role assigned to unauthenticated users**. The other role names are yours to choose.

#### Acl "Privileges"

[](#acl-privileges)

**IMPORTANT**: The third argument to `Acl::allow()`, 'privileges', is either a string or an array, and should be an HTTP verb or HTTP verbs respectively. By adding the third argument, you are restricting route access by HTTP method. If you do not provide an HTTP verb or verbs, you are allowing access to the specified route via *all* HTTP methods. **Be extremely vigilant here.** You wouldn't want to accidentally allow a 'guest' role access to an admin `DELETE`route simply because you forgot to explicitly deny the `DELETE` route.

Configuring Slim Auth: Defaults
-------------------------------

[](#configuring-slim-auth-defaults)

Now that you have a user database table with a `role` column and an ACL, you're ready to configure Slim Auth and add it to your application.

First, add `use` statements for the PasswordValidator (from the [Password Validator](https://github.com/jeremykendall/password-validator) library), the PDO adapter, and the Slim Auth Bootstrap.

```
use JeremyKendall\Password\PasswordValidator;
use JeremyKendall\Slim\Auth\Adapter\Db\PdoAdapter;
use JeremyKendall\Slim\Auth\Bootstrap;

```

Next, create your Slim application.

```
$app = new \Slim\Slim();

```

### Authentication Adapter

[](#authentication-adapter)

From the Zend Authentication documentation:

> `Zend\Authentication` adapters are used to authenticate against a particular type of authentication service, such as LDAP, RDBMS, or file-based storage.

Slim Auth provides an RDBMS authentication adapter for [PDO](http://php.net/manual/en/book.pdo.php). The constructor accepts five required arguments:

- A `\PDO` instance
- The name of the user table
- The name of the identity, or username, column
- The name of the credential, or password, column
- An instance of `JeremyKendall\Password\PasswordValidator`

```
$db = new \PDO();
$adapter = new PdoAdapter(
    $db,
    ,
    ,
    ,
    new PasswordValidator()
);

```

> **NOTE**: Please refer to the [Password Validator documentation](https://github.com/jeremykendall/password-validator) for more information on the proper use of the library. If you choose not to use the Password Validator library, you will need to create your own authentication adapter.

### Putting it all Together

[](#putting-it-all-together)

Now it's time to instantiate your ACL and bootstrap Slim Auth.

```
$acl = new \Namespace\For\Your\Acl();
$authBootstrap = new Bootstrap($app, $adapter, $acl);
$authBootstrap->bootstrap();

```

### Login Route

[](#login-route)

You'll need a login route, of course, and it's important that you name your route `login` using Slim's [Route Names](http://docs.slimframework.com/#Route-Names) feature.

```
$app->map('/login', function() {})->via('GET', 'POST')->name('login');

```

This allows you to use whatever route pattern you like for your login route. Slim Auth will redirect users to the correct route using Slim's `urlFor()`[Route Helper](http://docs.slimframework.com/#Route-Helpers).

Here's a sample login route:

```
// Login route MUST be named 'login'
$app->map('/login', function () use ($app) {
    $username = null;

    if ($app->request()->isPost()) {
        $username = $app->request->post('username');
        $password = $app->request->post('password');

        $result = $app->authenticator->authenticate($username, $password);

        if ($result->isValid()) {
            $app->redirect('/');
        } else {
            $messages = $result->getMessages();
            $app->flashNow('error', $messages[0]);
        }
    }

    $app->render('login.twig', array('username' => $username));
})->via('GET', 'POST')->name('login');

```

### Logout Route

[](#logout-route)

As authentication stores the authenticated user's identity, logging out consists of nothing more than clearing that identity. Clearing the identity is handled by `Authenticator::logout`.

```
$app->get('/logout', function () use ($app) {
    $app->authenticator->logout();
    $app->redirect('/');
});

```

And Done
--------

[](#and-done)

That should get you most of the way. I'll complete documentation as soon as I'm able, but can't currently commit to an ETA. Again, please feel free to open and issue with any questions you might have regarding implementation.

Thanks for considering Slim Auth for your project.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 97.1% 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 ~85 days

Recently: every ~76 days

Total

10

Last Release

3807d ago

Major Versions

0.0.7-alpha → 1.0.02016-01-03

1.0.1 → 2.0.0-alpha+0052016-01-23

PHP version history (3 changes)0.0.1-alphaPHP &gt;=5.3.3

0.0.3-alphaPHP &gt;=5.3.7

2.0.0-alpha+005PHP &gt;=5.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4232bff51ec1380e748a6829d6f98b88a15f16cc70af454da69d50c469d8c889?d=identicon)[jeremykendall](/maintainers/jeremykendall)

---

Top Contributors

[![jeremykendall](https://avatars.githubusercontent.com/u/288613?v=4)](https://github.com/jeremykendall "jeremykendall (99 commits)")[![do3meli](https://avatars.githubusercontent.com/u/1478176?v=4)](https://github.com/do3meli "do3meli (3 commits)")

---

Tags

authAuthenticationslimzendauthorizationzf2Zend Frameworkslim-framework

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[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.0M272](/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)[lorenzoferrarajr/lfj-opauth

LfjOpauth is a Zend Framework 2 module that enables support for many authentication providers through the Opauth framework.

2915.4k](/packages/lorenzoferrarajr-lfj-opauth)[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)
