Zend Framework authentication against database table

14 Nov

Zend Framework come with some built-in adapters. Buit-in adapter include database, LDAP, Http authentication adapter etc. I discussed how to create your own custom Authentication adapter in one of my previous post.
As most of the websites perform authentication against database. So better to discuss database authentication here in this post.
Zend_Auth_Adapter_DbTable provide you an ability to perform authentication against credential stored in database table.
Before writing the code, I would assume that you have done necessary configuration for database adapter in your bootfile. Study me post on Zend_config, if don’t know how to make database configuration.
After making the database configuration, store a reference to it using Zend_Registry.
Once you make the configuration in your bootstrap file. In your controller file, where you want to make authentication write the following code.

$db=Zend_Registry::get(‘db’);
$authAdapter= new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName(‘table_name’)

->setIdentityColumn(‘username’)
->setCredentialColumn(‘password’);

That’s it you have now defined everything. You will need to pass values posted via form as

$authAdapter->setIdentity($_POST[‘usrname’])

->setCredential($_POST[‘password’]);

And now simply pass this $authAdapter to authenticate() function as

$auth= new Zend_Auth();
$result=$auth->authenticate($authAdapter);

Now check if your authentication is valid

if($result->isValid()) {

$resultRow = $authAdapter->getResultRowObject();

}

You can place whatever code you want. Create your session and store this resultant row for future use.
Post questions if any.

4 Responses to “Zend Framework authentication against database table”

  1. speciman January 29, 2009 at 1:29 am #

    Hello,

    I believe the line :
    ->setIdentityColumn(‘password’);
    should read :
    ->setCredentialColumn(‘password’);

    Regards,

  2. Faheem Abbas January 29, 2009 at 6:45 am #

    Yeah. thanks for you correction. it was typo.

  3. heartbreaker June 7, 2009 at 11:05 pm #

    Hi,
    first of all thanks for your article. Now some feedback. I think there is typo in your code:

    $auth= new Zend_Auth();
    $result=$authenticate($authAdapter);

    should be:

    $auth= new Zend_Auth();
    $result=$auth->authenticate($authAdapter);

  4. raju March 3, 2010 at 11:18 am #

    It gives error : Call to protected Zend_Auth::__construct() from context ‘Admin_AuthController’

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

%d bloggers like this: