Using Zend Framework ACL and Auth to control access

I’ve recently started using the Zend framework components to produce a site I’m working on and thought I’d document how I’ve tied the Acl and Auth components together to control access.The site I’m building consists of several services which all have access through a common user account login, but with different classes of user. This seemed an ideal candidate for using Access control lists so I’ve set them up in the following way.

Each service is being written as a separate module in the application. Within the bootstrap.php file I’ve created a new Zend_Acl instance and added the various different classes of user who will be able to access the system

$acl = new Zend_Acl();
$acl->addRole(new Zend_Role('guest'))
    ->addRole(new Zend_Role('member'))
    ->addRole(new Zend_Role('admin'));

Then I've created a new Zend_Acl_Resource for each of the different applications i.e.

$acl->add(new Zend_Acl_Resource('module1'));
$acl->add(new Zend_Acl_Resource('module2'));
$acl->add(new Zend_Acl_Resource('module3'));
$acl->add(new Zend_Acl_Resource('module4'));

So now we have the basics set up we tie them together by telling the Acl
component which users can access which applications. First I deny access to all classes
 of user as a precaution

$acl->deny(null, null);

Then I assigned each application a class of user who is allowed to access the application.


So this is set up to allow all classes of user access to the module1 application, ‘member’ and ‘admin’ classes can access module2 and module3 applications and only class ‘admin’ can access the module4 application.

To use this I pass the ACL component to a front controller plugin which will check what class of user is identified and calls the $acl->isAllowed method to determine what to do with the user.

// Store the requested action to use after the user has logged on.
$AppRequest = new Zend_Session_Namespace(‘AppRequest’);
$AppRequest->module = $request->getModuleName();
$AppRequest->controller = $request->getControllerName();
$AppRequest->action = $request->getActionName();
$AppRequest->params = $request->getParams();

// Move to the login controller

In this code I store the request which the user made and then set the action to the appropriate one. In this case I move to the login module to get the user to authenticate , but if the user is already authenticated I could move the request to a module to just report to the user that they are not authorized to carry out that action.

Leave a Reply