Programming, Uncategorized

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:

        ROLE_USER:          ROLE_USER

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.