Authorisation on Roles in Symfony2
Following a discussion on the IRC room from someone who viewed my post about login/logout handlers in SF2, i wanted to clarify that when dealing with Roles, they should be dealt with in the controller actions.
For off, you need to make sure you got the right hierarchy of roles. In your app/config/security.yml you need something following the structure of:
security: role_hierarchy: ROLE_USER: ROLE_USER ROLE_MODERATOR: [ROLE_USER] ROLE_ADMIN: [ROLE_USER, ROLE_MODERATOR] ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_MODERATOR, ROLE_ADMIN]
Where the lowest level of access is at the top and the higher levels of access envelope the last levels of access.
Then you inside your controller actions you would do:
class fooController { public function showAction() { if ( ! $this->container->get('security.context')->isGranted('ROLE_USER')) { throw new AccessDeniedException('You do not have permission to use this resource!'); } } }
According the order of the role hierarchy if you have the role or higher than specified the controller action will continue, if you have a lower level of access than the minimum required then you will get an AccessDeniedException.
there are some blog posts that lack indentation
Question: Is there a way to move the role hierarchy into a database and then tell symfony load from the database on each load and not from the .yml file?
I know this will impact on performance, but it means you can have flexibility in managing custom roles in a system.
@Mark
Yes, this is possible. I believe this article should be of some use to you.
http://blog.jmoz.co.uk/symfony2-fosuserbundle-role-entities
how can you post something at 30 may 2012 if it’s 26 may?
@Ruben
Good question LOL. I think my Servers date/time settings are way out of whack. Odd as this is managed hosting so it should not be happening. Ill contact my ISP see if they can resolve it.
Thanks for pointing that out, i had not noticed.
From your post is not clear how the role is granted? But still thank you a lot! It is very nice concise explanation.