ArGh
ArGh

Reputation: 1168

Symfony roleHierarchy and controller security annotation

I have a role hierarchy defined in my security.yml config file :

role hierarchy:        
    ROLE_USER: [ROLE_USER]  
    ROLE_OFFICE: [ROLE_OFFICE]  
    ROLE_TEST: [ROLE_OFFICE, ROLE_USER]  

I want to use the security annotations in my controller :

/**
 * @Route("/office", name="office")
 * @Security("has_role('ROLE_OFFICE')")
 */

How can i use the role hierarchy with annotation. With my example, a user with ROLE_TEST will not be allowed to access my office route.

Thank you.

Upvotes: 1

Views: 170

Answers (3)

Matteo
Matteo

Reputation: 39470

If you want to exclude a route to a specific role you can negate the condition. As Example:

/**
 * @Route("/office", name="office")
 * @Security("not has_role('ROLE_TEST')")
 */

Hope this help

Upvotes: 0

jeremy
jeremy

Reputation: 319

If you change a little bit your annotation by :

@Security("is_granted('ROLE_OFFICE')")

Does the ROLE_TEST access the ressource?

Upvotes: 0

David Kmenta
David Kmenta

Reputation: 850

When you defining new role, you're defining from which existing role(s) will the role inherit. Your definition here is wrong.

  1. You don't have to define ROLE_USER, it will be defined once you extend it. (thanks to @Yonel)
  2. As I mentioned above, new role should extend existing one:

    role_hierarchy:
        ROLE_OFFICE: ROLE_USER  
        ...
    

    ROLE_OFFICE will also have the ROLE_USER

  3. Your ROLE_TEST now has also ROLE_OFFICE, this means that ROLE_TEST is allowed to access route /office. To fix this, you have to remove ROLE_OFFICE from your definition.


This should be working definition:

role_hierarchy:
    ROLE_OFFICE: ROLE_USER
    ROLE_TEST: ROLE_USER

Documentation: http://symfony.com/doc/current/security.html#hierarchical-roles

Upvotes: 2

Related Questions