Friday, April 29, 2011

How to add authentication in symfony for access rights - credentials

Today, I cam across issue where I needed to set access rights for certain user types in symfony for different modules.
Let me put up the steps and how it can be done:

First of all you need to make changes to security.yml in App directory:
/App/config/securiy.yml
For each module, depict whether it requires any authentication or not.

For example:
default:
  is_secure: false
modulename1:
  is_secure: true
modulename2:
  is_secure: true

Go to module where you require to have users based access
i.e App/[frontend | admin ]
in my case i wanted to set rights in frontend section:
so its apps/frontend/modules/config/security.yml
all:
  is_secure: true
  credentials: [ credentialname1, credentialname2 ]

if certain action requires authentication and certain not than:
for exmaple:
action1 and action2 below do not require any authentication where as remaining other requires authentication based on credentital.

actionname1:
  is_secure: false
actionname2:
  is_secure: true
  credentials: [ credentialname1 ]
all:
  is_secure: true
  credentials: [ credentialname2 ]

Now the final part is to assign credentials when user log-in to the system or application

Once authenticated, write the following code before any redirection:
$this->getUser()->addCredential('credentialname1');
OR
$this->getUser()->addCredential('credentialname2');

and finally, remember to clear the cache :)

Hope it helps
www.edugoog.com

No comments:

Post a Comment