Authentication with Zend Framework

Sonntag, 18.09.2011 | PHP | Keine Kommentare | php , zend framework

In this example I will show how to implement an authentication logic in Zend Framework with Zend_Auth. What we have is a module based MVC with two modules.

  • default - default module
  • restricted - restricted area (which needs authentication)

First of all we need a login action in our default module index controller for users to enter there credentails. In this example we authenticate against a Database Table where credentails are stored. There are more adapters available.

  • Database Table Authentication
  • Digest Authentication
  • HTTP Authentication Adapter
  • LDAP Authentication
  • Open ID Authentication
/* 
 * application/controllers/IndexController.php
 */
class IndexController extends Zend_Controller_Action
{
	public function loginAction()
    {
    	if($this->getRequest()->isPost()) {
    		$username = $this->_getParam('username', null);
    		$password = $this->_getParam('password', null);
    		
    		if(!is_null($username) && !is_null($password)) {
    			$dbAdapter = Zend_Registry::get('dbAdapter');
    			$authAdapter = new Zend_Auth_Adapter_DbTable(
				    $dbAdapter,
				    'users',     // Table name
				    'username',  // Idenitity column
				    'password'   // Password column
				);
				$authAdapter->setIdentity($username)->setCredential(md5($password));
				
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				
				if ($result->isValid()) {
					// Print the result row
					//print_r($authAdapter->getResultRowObject());
					$this->_forward('index', 'index', 'restricted');
					return;
				} else {
					echo 'invalid username/password';
				}
    		} else {
    			echo 'username/password is empty';
    		}
    	}
    }
}

Anyway if result is valid we can forward user to the restricted area (line 28).

Now we have to check if user is logged in. As we need to do this on every page it is a good idea to use a plugin. So let's create an authentication plugin.

/* 
 * library/My/Plugin/Auth.php
 */
class My_Plugin_Auth extends Zend_Controller_Plugin_Abstract 
{
	public function preDispatch()
	{
		$module = $this->getRequest()->getModuleName();
		if($module == 'restricted') {
			$auth = Zend_Auth::getInstance();
			if(!$auth->hasIdentity()) {
			 	$this->getRequest()->setModuleName('default');
			 	$this->getRequest()->setControllerName('index');
			 	$this->getRequest()->setActionName('login');
			}
		}
	}
}

If user has no identity and tries to view a page in the restricted area he will be redirected to the login page. To register this plugin we need to add the following line to our application.ini.

resources.frontController.plugins.one = "My_Plugin_Auth"

As Zend_Auth is implemented as singleton you can access it from everywhere. You can check if user has identity with following method:

Zend_Auth::getInstance()->hasIdentity()

Share