Set Credentials using security.yml in Symfony 1.4
anoopsachari | May 28, 2010 | Comments 3
Symfony provides some cool configuration features that would allow you to minimize your coding part . In this tutorial i would explain how to configure security.yml to set credentials for a different users.
Create a class file named account.class.php under apps/frontend/lib folder with content .The class below checks weather the user is admin and sets his credential as ‘admin’ . Update the class file as your requirement .
class account
{
public static function getLoginAdmin($username, $password)
{
// code to check for username and password in a particular table : ORM is doctrine
$usr = Doctrine::getTable('TableName')
->createQuery('a')
->where('a.adminuser = ?',$username)
->andWhere('a.password = ?',$password)
->execute();
$login_user = count($usr);
if($login_user > 0)
{
sfContext::getInstance()->getUser()->setAuthenticated(true);
sfContext::getInstance()->getUser()->addCredential('admin');
return true;
}
else
{
return false;
}
}
public static function LogoutSession()
{
sfContext::getInstance()->getUser()->setAuthenticated(false);
sfContext::getInstance()->getUser()->clearCredentials();
sfContext::getInstance()->getUser()->getAttributeHolder()->removeNamespace('admin');
return true;
}
}
And in login action file after receiving username and password call the library function as shown below
$login_flag = account::getLoginAdmin($this->username,$this->password);
and if $login_flag returns true you have successfully logged in else enter username or password is invalid .
You have done with the class file and action page . Now you need to configure security.yml .
Create a folder named config inside a module ( say for eg : under admin module ) with security.yml in it and paste the following code .
index: is_secure: true credentials: admin
Now admin module can be accessed only by one with ‘admin’ credential .
You can flush the credential as
$logout = account::LogoutSession();
You are done !
About the Author: a holistic web developer , movie buff and technical blogger from queen of arabian sea.








Hi, is very easy the example i understand all code but the implementation in my app-symfony not give me good results. (sorry for my bad english). I follow line to line the code but i have problem with the credentials. I setup all configuration files of my app and not find the solution. When redirect to another module (module “sala”) gives me a message saying “Credential Required. This page is in a restricted area.” and it is very strange because when the user login credentials I setup to “admin” and the module “sala” I allow users to enter credentials “admin” and although I’ve tried changing some things it still does not work. I hope help me.
Thanks.
i think the error is due to the security.yml file . where did you create it ?
This security.yml configuration reference could be useful: http://www.symfonyreference.com/security-yml