Managing User Sessions In ZF

Authenticating Users in Zend Framework

Introduction to Authentication

Once a web application has been able to distinguish one user from another by establishing a session, web applications typically want to validate the identity of a user. The process of validating a consumer as being authentic is "authentication." Authentication is made up of two distinctive parts: an identity and a set of credentials. It takes some variation of both presented to the application for processing so that it may authenticate a user.

While the most common pattern of authentication revolves around usernames and passwords, it should be stated that this is not always the case. Identities are not limited to usernames. In fact, any public identifier can be used: an assigned number, social security number, or residence address. Likewise, credentials are not limited to passwords. Credentials can come in the form of protected private information: fingerprint, eye retinal scan, passphrase, or any other obscure personal information.

Basic Usage of Zend_Auth

In the following example, we will be using Zend_Auth to complete what is probably the most prolific form of authentication: username and password from a database table. This example assumes that you have already setup your application using Zend_Application, and that inside that application you have configured a database connection.

The job of the Zend_Auth class is twofold. First, it should be able to accept an authentication adapter to use to authenticate a user. Secondly, after a successful authentication of a user, it should persist throughout each and every request that might need to know if the current user has indeed been authenticated. To persist this data, Zend_Auth consumes Zend_Session_Namespace, but you will generally never need to interact with this session object.

Lets assume we have the following database table setup:

  1. CREATE TABLE users (
  2.     id INTEGER  NOT NULL PRIMARY KEY,
  3.     username VARCHAR(50) UNIQUE NOT NULL,
  4.     password VARCHAR(32) NULL,
  5.     password_salt VARCHAR(32) NULL,
  6.     real_name VARCHAR(150) NULL
  7. )

The above demonstrates a user table that includes a username, password, and also a password salt column. This salt column is used as part of a technique called salting that would improve the security of your database of information against brute force attacks targeting the algorithm of your password hashing. » More information on salting.

For this implementation, we must first make a simple form that we can utilized as the "login form". We will use Zend_Form to accomplish this.

  1. // located at application/forms/Auth/Login.php
  2.  
  3. class Default_Form_Auth_Login extends Zend_Form
  4. {
  5.     public function init()
  6.     {
  7.         $this->setMethod('post');
  8.  
  9.         $this->addElement(
  10.             'text', 'username', array(
  11.                 'label' => 'Username:',
  12.                 'required' => true,
  13.                 'filters'    => array('StringTrim'),
  14.             ));
  15.  
  16.         $this->addElement('password', 'password', array(
  17.             'label' => 'Password:',
  18.             'required' => true,
  19.             ));
  20.  
  21.         $this->addElement('submit', 'submit', array(
  22.             'ignore'   => true,
  23.             'label'    => 'Login',
  24.             ));
  25.  
  26.     }
  27. }

With the above form, we can now go about creating our login action for our authentication controller. This controller will be called "AuthController", and will be located at application/controllers/AuthController.php. It will have a single method called " loginAction()" which will serve as the self-posting action. In other words, regardless of the url was POSTed to or GETed to, this method will handle the logic.

The following code will demonstrate how to construct the proper adapter, integrate it with the form:

  1. class AuthController extends Zend_Controller_Action
  2. {
  3.  
  4.     public function loginAction()
  5.     {
  6.         $db = $this->_getParam('db');
  7.  
  8.         $loginForm = new Default_Form_Auth_Login();
  9.  
  10.         if ($loginForm->isValid($_POST)) {
  11.  
  12.             $adapter = new Zend_Auth_Adapter_DbTable(
  13.                 $db,
  14.                 'users',
  15.                 'username',
  16.                 'password',
  17.                 'MD5(CONCAT(?, password_salt))'
  18.                 );
  19.  
  20.             $adapter->setIdentity($loginForm->getValue('username'));
  21.             $adapter->setCredential($loginForm->getValue('password'));
  22.  
  23.             $auth   = Zend_Auth::getInstance();
  24.             $result = $auth->authenticate($adapter);
  25.  
  26.             if ($result->isValid()) {
  27.                 $this->_helper->FlashMessenger('Successful Login');
  28.                 $this->_redirect('/');
  29.                 return;
  30.             }
  31.  
  32.         }
  33.  
  34.         $this->view->loginForm = $loginForm;
  35.  
  36.     }
  37.  
  38. }

The corresponding view script is quite simple for this action. It will set the current url since this form is self processing, and it will display the form. This view script is located at application/views/scripts/auth/login.phtml:

  1. $this->form->setAction($this->url());
  2. echo $this->form;

There you have it. With these basics you can expand the general concepts to include more complex authentication scenarios. For more information on other Zend_Auth adapters, have a look in the reference guide.


Managing User Sessions In ZF