jump to navigation

Zend Framework: Getting Started with Zend_Auth May 10, 2011

Posted by Tournas Dimitrios in Zend Framework v1.10.
trackback

This article is intended to present the  basics concepts of integrating Zend_Auth into an Zend application . Although the official site provides an extensive reference  guide , a newcomer to the Zend Framework , may feel lost with all the technical jargons and cross references . My approach is to provide the basic concepts , so that newcomers can get started .

Zend_Auth is responsible for authentication which is the process of identifying an individual ( entity ) based on their credentials (usually a username and password) . A complementary part to authentication is authorization which decides what permissions  on what resources of the  Zend Application  , that specific entity will have .  Authorization is provided from another Zend module ( Zend_Acl ) , which is a subject for a future article . Usually  Zend applications combines  Zend_Auth and Zend_Acl , but for starters let’s take only one step at a time .

Zend_Auth is separated into a core component and a set of adapters. These adapters will contain configuration options ( credentials )  for connecting to a given authentication storage . These configuration option values may be passed to the constructor or deferred as parameters to setter methods after instantiation . Different adapters are likely to have vastly different  configuration options and behaviors , but some basic things are common among them .For example all adapters return a adapter resource . This resource will be used from the Zend_Auth instance to query the Authentication storage  and finally a Zend_Auth_Result object will be returned  .With that object  we can : track if the authentication is failed or success , get error code messages and  , upon successful authentication , even store the values of the Table row (getResultRowObject() )  to a persistent storage mechanism of Zend_Auth ( getStorarage() )  for later use. For security reasons , a good practice would be to exclude the password column field from the persistent storage . Advanced users can  create their own adapters  , but for now , let’s just use  one of Zend’s build-in  adapters :

  • Zend_Auth_Adapter_DbTable : Provides the ability to authenticate against credentials stored in a database . This article is focused on this adaptor as it  is the most used
  • Zend_Auth_Adapter_Digest :  This is a HTTP authentication method , but passwords are not transmitted in clear text .
  • Zend_Auth_Adapter_Http: This method  improves upon basic HTTP authentication
  • Zend_Auth_Adapter_Ldap : Authentication with LDAP services ( Linux administrators should be  familiar with LDAP )
  • Zend_Auth_Adapter_OpenId :  Authenticate users using remote OpenID servers ( probably this method of authentication will dominate in the future )

In this article , we will look at what needs to be done to log in using authentication against credentials stored in a Database table ( Zend_Auth_Adapter_DbTable) . One thing to mention here :  Zend_Auth implements the ” singleton pattern ”  , that means that there can only be one instance of the class . To get a handle to that instance , we use the static method  Zend_Auth::getInstance() . The steps that must be followed :

  1. Create a “authusers ” table inside the database
  2. Define credentials for the Database connection in the general configuration file ( application/configs/application.ini)
  3. Create a Form Class
  4. Create a Controller that will handle the Authentication proccess

1. Create a “authusers ” table inside the database :

This article takes the most basic implementation , just to focus on the core functionality of the Zend_Auth component . Usually  , for security reasons , the password field will be encrypted  ( MD5 , SHA …  )  . This is the schema of our Database table .

CREATE TABLE IF NOT EXISTS authusers (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(30) NOT NULL,
  password varchar(30) NOT NULL,
  PRIMARY KEY (id)
)

2. Define credentials for the Database connection :

A good practice is to store the Database credentials on a central point  , so application.ini file is ideal for this . We could of course manually set these configuration options , but the Zend tool makes our job simpler . zf configure dbadapter “adapter=pdo_mysql&username=root&password=”&dbname=test&hostname=localhost” production

3. Create a Form Class:

If you need a refresh for the Zend_Form component  read my previous article

4 . Create a Controller that will handle the Authentication process :

This is the most important part of this article , read it twice so that the basic concepts are clearly understood .. As mentioned previously , authentication is made from 2 parts :

  • A  Zend_Adapter_xxxxx  interface .
  • An instance of Zend_Auth

As for this article  a Database is used  for  Authentication storage   , Zend_Auth_Adapter_DbTable  is the interface . Connecting to a Database demands the appropriate credentials ( username , location , password , dbname ) . Our general configuration file “application/configs/application.ini ” is already configured with  these credentials (see step 2 above ) and Zend_Db_Table::getDefaultAdapter  will recover them . The next step is to define which table from the Database to use and what columns are registered as containers for username and password  . Finally the adaptor will return  an db resource adapter  .

protected function _getAuthAdapter()
    {
        $authAdapter = new Zend_Auth_Adapter_DbTable(
						Zend_Db_Table::getDefaultAdapter()
						);
        $authAdapter->setTableName('authusers')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password');
        return $authAdapter;
    }

The resource adapter returned from Zend_Adapter_DbTable will be used from Zend_Auth instanse . Here comes the point of the actual authentication , calling authenticate() , will return  a Zend_Auth_Result  object . From this object  , we can extract several different information like pass/failed , error-codes , error-messages and even the data that the table contains ….  But in our case we are looking for a simple pass/failed  , so we are ignoring the rest . In a real application however , you would want to check the errors and throw an exception should thinks go wrong . Here is the code of the Zend_Adapter instance .

protected function _getAuthInstance($values)
    {
        $adapter = $this->_getAuthAdapter();
        $adapter->setIdentity($values['username']);
        $adapter->setCredential($values['password']);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if ($result->isValid()) {
            return true;
        }
        return false;
    }

Finally the central part of our authentication . This part will take decisions based on three nested if-statements . The firs statement checks whether POST variables are included in the request , if passed , the second statement will check whether the POST variables are valid , if passed , the last statement will enable the Authentication process . The predefined redirection will take action if the Authentication process returns a true value else the form will be displayed .

public function indexAction()
    {
        $form = new Application_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($this->_getAuthInstance($form->getValues())) {
                   $this->_helper->redirector('index', 'Loged-In');
                } else {
               echo " Invalid Credentials Please tray again!!! " ;
// A better option for displaying the invalid submit
$this->view->errorMessage = " Invalid Credentials ....... " ;
// Display the errorMessage in the view is simple
// echo $this->errorMessage ;
                }
            }
        }
        $this->view->form = $form;
    }

Here is the code of the Auth Controller :

class AuthController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $form = new Application_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($this->_getAuthInstance($form->getValues())) {
                   $this->_helper->redirector('index', 'Loged-In');
                }
            }
        }
        $this->view->form = $form;
    }

    protected function _getAuthInstance($values)
    {
        $adapter = $this->_getAuthAdapter();
        $adapter->setIdentity($values['username']);
        $adapter->setCredential($values['password']);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if ($result->isValid()) {

            return true;
        }
        return false;
    }

    private function _getAuthAdapter()
    {
        $authAdapter = new Zend_Auth_Adapter_DbTable(
						Zend_Db_Table::getDefaultAdapter()
						);
        $authAdapter->setTableName('authusers')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password');
        return $authAdapter;
    }

}

Download the project code of this article >>>>>>

Further reading :

Comments»

1. Amine - May 19, 2011

Thank you for the tutorial and the project code ! Was looking for a smooth way of authentifying users on my test website and this looks promising 🙂
Will keep you updated

tournasdimitrios1 - May 19, 2011

@Amine
I’m glad it was helpful to you .


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s