Zend Framework authentication against database table
Posted by Faheem Abbas on November 14, 2008
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.
speciman said
Hello,
I believe the line :
->setIdentityColumn(‘password’);should read :
->setCredentialColumn(‘password’);Regards,
Faheem Abbas said
Yeah. thanks for you correction. it was typo.
heartbreaker said
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);