Zend Authentication and Authorization Tutorial with Zend_Auth and Zend_Acl

Here is a short tutorial showing you how to set up Zend_Auth and Zend_Acl in your project. As you know, Zend_Auth deals with the authentication and Zend_Acl deals with the authorization for your application.

The most common scenario is to have the users in a database table, so let’s start by creating the model files for this. The user table will have 4 columns: id, email, password and role. The role column will keep values like ‘user’, ‘admin’, ‘superadmin’ or whatever you need for user separation in your application. This will be used by ACL to differentiate between users who can or not access specific resources.

First we create a Table Data Gateway to connect to our data source:

// application/models/DbTable/User.php
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
    protected $_name = 'user';
    protected $_primary = 'id';
}

After that we need a Data Mapper class for our User objects:

// application/models/UserMapper.php
class Application_Model_UserMapper
{
    protected $_dbTable;

    protected function _hydrate($row)
    {
        $user = new Application_Model_User();
        $user->setId($row->id)
             ->setEmail($row->email)
             ->setPassword($row->password)
             ->setRole($row->role);

        return $user;
    }

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;

        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_User');
        }

        return $this->_dbTable;
    }

    public function save(Application_Model_User $user)
    {
        $data = array(
            'email'       => $user->getEmail(),
            'password'    => $user->getPassword(),
            'role'        => $user->getRole()
        );

        if (null === ($id = $user->getId())) {
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();

        return $this->_hydrate($row);
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entries[] = $this->_hydrate($row);
        }

        return $entries;
    }
}

And, of course, the User class:

// application/models/User.php
class Application_Model_User
{
    protected $_id;
    protected $_email;
    protected $_password;
    protected $_role;

    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }

        return $this;
    }

    public function setId($id)
    {
        $this->_id = (int) $id;

        return $this;
    }

    public function getId()
    {
        return $this->_id;
    }

    public function setEmail($email)
    {
        $this->_email = (string) $email;

        return $this;
    }

    public function getEmail()
    {
        return $this->_email;
    }

    public function setPassword($password)
    {
        $this->_password = (string) $password;

        return $this;
    }

    public function getPassword()
    {
        return $this->_password;
    }

    public function setRole($role)
    {
        $this->_role = (string) $role;

        return $this;
    }

    public function getRole()
    {
        return $this->_role;
    }
}

Let’s now create an AuthController in our application that will hold the login and logout actions:

// application/controllers/AuthController.php
class AuthController extends Zend_Controller_Action
{
    public function loginAction()
    {
        $users = new Application_Model_DbTable_User();
        $form = new Application_Form_LoginForm();
        $this->view->form = $form;
        if($this->getRequest()->isPost()) {
            if($form->isValid($_POST)) {
                $data = $form->getValues();
                $auth = Zend_Auth::getInstance();
                $authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'user');
                $authAdapter->setIdentityColumn('email')->setCredentialColumn('password');
                $authAdapter->setIdentity($data['email'])->setCredential($data['password']);
                $result = $auth->authenticate($authAdapter);
                if($result->isValid()) {
                    $storage = new Zend_Auth_Storage_Session();
                    $storage->write($authAdapter->getResultRowObject());
                    $mysession = new Zend_Session_Namespace('mysession');
                    if(isset($mysession->destination_url)) {
                        $url = $mysession->destination_url;
                        unset($mysession->destination_url);
                        $this->_redirect($url);
                    }
                    $this->_redirect('index/index');
                } else {
                    $this->view->errorMessage = "Invalid email or password. Please try again.";
                }
            }
        }
    }

    public function logoutAction()
    {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        $this->_redirect('index/index');
     }
}

The view for the login action is listed below:

<!-- application/views/scripts/auth/login.phtml -->
<?php if(isset($this->errorMessage)): ?>
    <?php echo $this->errorMessage; ?>
<?php endif; ?>

<?php echo $this->form; ?>

The login form used above is here:

// application/forms/LoginForm.php
class Application_Form_LoginForm extends Zend_Form
{
    public function init()
    {
        $email = $this->createElement('text','email');
        $email->setLabel('Email: *')
              ->setRequired(true);

        $password = $this->createElement('password','password');
        $password->setLabel('Password: *')
                 ->setRequired(true);

        $signin = $this->createElement('submit','signin');
        $signin->setLabel('Sign in')
               ->setIgnore(true);

        $this->addElements(array(
            $email,
            $password,
            $signin,
        ));
    }
}

For the ACL we will use a Front Controller Plugin to secure the entire application:

// library/My/Controller/Plugin/ACL.php
class My_Controller_Plugin_ACL extends Zend_Controller_Plugin_Abstract
{
    protected $_defaultRole = 'guest';

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $auth = Zend_Auth::getInstance();
        $acl = new My_Acl();
        $mysession = new Zend_Session_Namespace('mysession');

        if($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if(!$acl->isAllowed($user->role, $request->getControllerName() . '::' . $request->getActionName())) {
                $mysession->destination_url = $request->getPathInfo();

                return Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->setGotoUrl('auth/noauth');
            }
        } else {
            if(!$acl->isAllowed($this->_defaultRole, $request->getControllerName() . '::' . $request->getActionName())) {
                $mysession->destination_url = $request->getPathInfo();

                return Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->setGotoUrl('auth/login');
            }
        }
    }
}

The Acl class, that will define resources and levels of authorization, is next:

// library/My/Acl.php
class My_Acl extends Zend_Acl
{
    public function __construct()
    {
        // Add a new role called "guest"
        $this->addRole(new Zend_Acl_Role('guest'));
        // Add a role called user, which inherits from guest
        $this->addRole(new Zend_Acl_Role('user'), 'guest');
        // Add a role called admin, which inherits from user
        $this->addRole(new Zend_Acl_Role('admin'), 'user');

        // Add some resources in the form controller::action
        $this->add(new Zend_Acl_Resource('error::error'));
        $this->add(new Zend_Acl_Resource('auth::login'));
        $this->add(new Zend_Acl_Resource('auth::logout'));
        $this->add(new Zend_Acl_Resource('index::index'));

        // Allow guests to see the error, login and index pages
        $this->allow('guest', 'error::error');
        $this->allow('guest', 'auth::login');
        $this->allow('guest', 'index::index');
        // Allow users to access logout and the index action from the user controller
        $this->allow('user', 'auth::logout');
        $this->allow('user', 'user::index');
        // Allow admin to access admin controller, index action
        $this->allow('user', 'admin::index');

        // You will add here roles, resources and authorization specific to your application, the above are some examples
    }
}

Now, to enable the plugin we created, we need to add to the application bootstrap file the following:

// application/Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initPlugins()
    {
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('My_');

        $objFront = Zend_Controller_Front::getInstance();
        $objFront->registerPlugin(new My_Controller_Plugin_ACL(), 1);
        return $objFront;
    }
}

After this, every time a user access you application, the ACL will check the role of the user and send him to the login form if he is not authenticated or to the auth/noauth page if he has no right seeing that page.

11 thoughts on “Zend Authentication and Authorization Tutorial with Zend_Auth and Zend_Acl

  1. Thank you for this nice tutorial. Would you consider sharing the full project code for this example on a code-sharing site such as GitHub, Bitbucket, etc.? That would be extremely helpful.

  2. I like this tutorial… helped me create my first zend auth and acl based login however could you extend this tutorial slightly to explain

    (a) How to include all actions under one controller to a User authorization level. i.e. I have a masters controller which has numerous actions under it for various tables. Could you tell me how to restrict access to Masters controller all actions to admin role only. Without adding resources and allow resources for each action in Acl.php

    (b) If you could extend this tutorial to registeration of users by providing details and approval by admin role for access to the site.

  3. Thank You! Finally, an easy to follow guide to ACL using Zend. I’ve been banging my head against the wall trying to follow the other tutorials out there. This took me 20 mins to get working and it couldn’t be easier.

  4. Hi
    It gives an error.
    Class ‘My_Acl’ not found in D:\xampp\htdocs\tech2soft\library\My\Controller\plugin\acl.php on line 9

Leave a Reply

Your email address will not be published. Required fields are marked *


× three = 24

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>