Slim Auth is an authorization and authentication library for the Slim Framework.

Overview

Slim Auth Build Status Coverage Status Dependencies Status

Slim Auth is an authorization and authentication library for the Slim Framework. Authentication is provided by the Zend Framework Zend\Authentication component, and authorization by the Zend Framework Zend\Permissions\Acl component.

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 and Zend\Permissions\Acl, 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

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 >= 2.6.

Earlier versions of this documentation (and the sample implementation) demonstrated the use of Slim's SessionCookie Middleware as a way to handle session storage in concert with Zend Session. As of Slim 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

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

Example Implementation

I've put together an example implementation to demonstrate the library in action. The example implementation can be found here.

Installation

Installation is provided via Composer.

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

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

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 for complete details on using the Zend Framework ACL component.

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'); } }">
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

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"

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

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

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. 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 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

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

You'll need a login route, of course, and it's important that you name your route login using Slim's 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.

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

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

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.

Comments
  • Authentication failing(3.x)

    Authentication failing(3.x)

    Hi Jeremy, I have implemented the build for Slim 3.x, but I am having an issue with the authentication. When I send a username and password, it returns as a failed login attempt. I am not sure why. It is checking the correct table and columns for identity and credentials. Password is currently hashed as MD5. A role is set(admin).

    No errors are being thrown by PHP. How can I go about figuring out what could be causing it to fail? Happy to share any code that would help.

    question Slim 3.x 
    opened by MLGeorge88 12
  • Throw http 401 rather than redirect to 'login'

    Throw http 401 rather than redirect to 'login'

    Hi!

    I'm currently using SLIM 2 for creating a rest api which needs authentication and authorization - and decided to give your plugin a spin.

    However, I find it suboptimal that the authentication performs a redirect to 'login' when the user is not logged in - it would be much nicer if it just returned a 401, to show the consumers of the API that authentication is required.

    Perhaps it could be configurable in the Bootstrapper? Like, adding an configuration array as a 4'th optional argument

    $acl = new \My\ApiAcl();
    $authBootstrap = new Bootstrap($app, $adapter, $acl, array(
       'disableAuthRedirect'  => true
    ));
    $authBootstrap->bootstrap();
    

    Or similar :)

    enhancement 
    opened by nover 11
  • Vendor name conflict

    Vendor name conflict

    Hello,

    since we use Slim Auth, we got the following error while composer install/update:

    Skipped installation of bin bin/version-check for package jeremykendall/slim-auth: name conflicts with an existing file

    Any idea?

    enhancement question 
    opened by solidevolution 9
  • Fix composer update issue

    Fix composer update issue

    The version string is invalid which makes composer update break with:

    [RuntimeException]
    Could not load package jeremykendall/slim-auth in http://packagist.org: [UnexpectedValueException] Could not parse version constraint ^2.4.2: Invalid version string "^2.4.2"

    wontfix 
    opened by nover 8
  • Incompatibility with PHP 5.4?

    Incompatibility with PHP 5.4?

    I'm running PHP Version 5.4.25-1+sury.org~precise+2

    Catchable fatal error: Argument 1 passed to JeremyKendall\Slim\Auth\Middleware\Authorization::__construct() must be an instance of Zend\Authentication\AuthenticationService, instance of Closure given, called in /var/www/vendor/jeremykendall/slim-auth/src/JeremyKendall/Slim/Auth/Bootstrap.php on line 142 and defined in /var/www/vendor/jeremykendall/slim-auth/src/JeremyKendall/Slim/Auth/Middleware/Authorization.php on line 49

    opened by hugofcampos 8
  • Why no 3.0 ;-)

    Why no 3.0 ;-)

    Hey @jeremykendall ,

    Have you got any plans for 3.0 ?

    I would like to investigate on my free time. Let me know if I can help you with :-) .

    Thank you.

    question Slim 3.x 
    opened by harikt 7
  • Route for login

    Route for login

    As I'm using slim only for my api I would like to have my login also nested in the url like that: /api/v1/login

    implemented like that:

    // General API group
    $app->group(
        '/api',
        function () use ($app, $log) {
    
            // Common to all sub routes
    
            // Get contacts
            $app->get('/', function () {
              echo stripslashes(file_get_contents("docs/index.html"));
            });
    
            // Group for API Version 1
            $app->group(
                '/v1',
                // API Methods
                function () use ($app, $log) {
    
                    $app->post(
                      '/login',
                      function () use ($app,$log){
                        $json = $app->request->getBody();
                        $result = $app->authenticator->authenticate($json->username, $json->password);
                        if ($result->isValid()) {
                          echo json_encode(true, JSON_PRETTY_PRINT);
                        } else {
                          echo json_encode(false, JSON_PRETTY_PRINT);
                        }
                      }
                    );
    

    But slim-auth says it can't find a login route.. And another question I would like to use a token system so giving the user a token back after login which a middleware should check..

    Cheers Marv

    question 
    opened by marvinosswald 6
  • Session issues

    Session issues

    Hi.

    I followed your README to setup slim-auth. Now I have some issues with session persistence - I created admin user and I can log in with it.

    However if I try to use some protected routing, the session could not remember that user is logged in.

    I followed the code and tried to understand, whats wrong. So I found out that if AuthorizationMiddleware is initialized, it will get $auth and $acl objects. In AuthorizationMiddleware's constructor function the $auth->getStorage()->read() will reveal the correct session data. Now if I debugged the AuthorizationMiddleware call() method then $this->auth->getStorage()->read() is empty. I cannot figure out what's wrong with it.

    bug 
    opened by Siim 4
  • hasIdentity and hooks in slim3

    hasIdentity and hooks in slim3

    Hi

    Since Slim 3 has no more Hooks, how can I test hasIdentity in a twig view on slim 3? Seems to me that I need to translate the $app->hook (...) into a Middleware, any Ideas?

    question Slim 3.x 
    opened by Bigua 3
  • Documentation / example code

    Documentation / example code

    Hi, I wanted to try out this code but I'm bit stuck. In your readme there is an example code which uses Bootstrap class which is not present anymore. Can you please update your example code?

    question documentation 
    opened by jernejsk 3
  • determineRouteBeforeAppMiddleware

    determineRouteBeforeAppMiddleware

    I'd like just to note that for slim 3.x, the parameter determineRouteBeforeAppMiddlewareneed to be set to trueduring startup, otherwise the auth middleware cannot determine the current route. It should be stated in the docs.

    Thanks for your great work! Urs

    documentation Slim 3.x 
    opened by urshofer 3
  • Documentation to use with slim 3?

    Documentation to use with slim 3?

    Hey @jeremykendall,

    I need to update my app from slim 2 to slim 3 and happily used slim-auth. Now that I need to upgrade slim to version 3 I tried to find some documentation on how to use slim-auth with slim 3 but unfortunately without luck. The Readme still explains usage with slim 2.

    Do you have an idea on how to integrate slim-auth with slim 3?

    opened by Regaddi 0
  • Error creating class

    Error creating class

    I am passing this $app = new \Slim\App($settings); $authBootstrap = new Bootstrap($app, $adapter, $acl);

    and getting this error

    Fatal error: Uncaught TypeError: Argument 1 passed to JeremyKendall\Slim\Auth\Bootstrap::__construct() must be an instance of Slim\Slim, instance of Slim\App given

    It seems that Slim3 is not using Slim as main class name but App.

    opened by scriptburn 0
  • [Q] How does authentication work internally

    [Q] How does authentication work internally

    I would like to use this to authenticate my slim REST API but I'm a bit confused right now.

    Don't I have to add an accessToken or something like this to my response from login? If a user calls login and after that tries to get some other data how does the system know that the user is authenticated and allowed to call the method? Of course then I have to test if the accessToken is valid in each route but it seams that I do not have to do all this by myself.

    The only way I could think of is that the authentication is IP based but I see some problems with that so that could not be the answer, right?

    Also how long is the authentication valid? Can I set a experation date somewhere?

    opened by Cilenco 0
  • Ldap

    Ldap

    Hi, I've successfully integrated this auth in my slim 3 app, now its time to move forward and put it to work with LDAP, any thoughts or tips in how to do this?

    Searching the internet i've found this repo https://github.com/marcelbonnet/slim-auth, who is using parts of this module.. but they put it to work together with doctrine.. but I'm using eloquent.

    Tnx

    opened by Bigua 0
  • composer install incomplete?

    composer install incomplete?

    Hi,

    do I miss something here? SlimAuthProvider Class etc. is not getting downloaded. My composer.json includes "jeremykendall/slim-auth": "2.0.0-alpha".

    opened by ghost 4
Releases(2.0.0-alpha+005)
Owner
Jeremy Kendall
Jeremy Kendall
Files Course Laravel Micro Auth and Authorization

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

EspecializaTi 8 Oct 22, 2022
Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

Rizky Kurniawan 12 Oct 10, 2022
Multi Auth and admin auth in Laravel Project

Laravel Multi Auth For Complete Documentation, visit Here This package is just create admin side (multi auth), which is totaly isolated from your norm

Bitfumes 435 Dec 31, 2022
A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

null 2 Jun 6, 2022
A framework agnostic authentication & authorization system.

Sentinel Sentinel is a PHP 7.3+ framework agnostic fully-featured authentication & authorization system. It also provides additional features such as

Cartalyst 1.4k Dec 30, 2022
CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Cake Development Corporation 24 Sep 23, 2022
Authentication, authorization and access control for PHP

Jasny Auth Authentication, authorization and access control for PHP. Features Multiple authorization strategies, like groups (for acl) and levels. Aut

Arnold Daniels 105 Dec 12, 2022
A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Damiano Petrungaro 58 Aug 10, 2022
This is a basic Oauth2 authorization/authentication server implemented using Mezzio.

Mezzio-OAuth2-Authorization-Authentication-Server This is a basic OAuth2 authorization/authentication server implemented using Mezzio. I have found so

null 1 Nov 15, 2022
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
Aplicação criada com Slim Framework com objetivo de criar autenticação com JWT e aprender sobre o framework Slim

Slim JWT App Essa aplicação tem como foco o aprendizado do Framework Slim e também a utilização de JWT. Como rodar a Aplicação A aplicação está config

Nicolas Pereira 9 Oct 4, 2022
phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

Apereo Foundation 780 Dec 24, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .

PHP-Casbin Documentation | Tutorials | Extensions Breaking News: Laravel-authz is now available, an authorization library for the Laravel framework. P

PHP-Casbin 1.1k Dec 14, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

Laravel Authorization Laravel-authz is an authorization library for the laravel framework. It's based on Casbin, an authorization library that support

PHP-Casbin 243 Jan 4, 2023
An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

PHP-Casbin 18 Dec 30, 2022
It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session and API Authentication

About Auth Starter It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session an

Sami Alateya 10 Aug 3, 2022
Rinvex Authy is a simple wrapper for @Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

Rinvex Authy Rinvex Authy is a simple wrapper for Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest AP

Rinvex 34 Feb 14, 2022
Simple JWT Auth support for Laravel PHP Framework

Laravel JWT Simple JWT Auth for Laravel PHP Framework using Firebase JWT under the hood. Installation Standard Composer package installation: composer

Ricardo Čerljenko 34 Nov 21, 2022
Simple PASETO Auth support for Laravel PHP Framework

Laravel PASETO Simple PASETO Auth for Laravel PHP Framework using paragonie/paseto under the hood. Installation Standard Composer package installation

Ricardo Čerljenko 9 Jan 11, 2022