Search code examples
symfonyuser-roles

How to create and register new roles in Symfony2


I see from the official Symfony2 doc on Security that new roles can be defined besides the "classical" ones (i.e. ROLE_USER, ROLE_ADMIN, etc.).

How can I define new roles and register them to my Symfony2 application in order to create roles hierarchy in the security.yml?

Sorry to have bothered all of you! I think that the answer is simple. In fact, it seems that is sufficient to start to use a new role by starting the name with ROLE_. E.g., it is possible to say ROLE_NEWS_AUTHOR to let only people with that role to be capable to insert a news in the website.

Thanks.


Solution

  • Sure you can simply add any roles starting with ROLE_SOMEROLE.In security.yml file there are two main part to 1.limit the access 2. Who are the memebers can access

    a. access_control: Which limit the pattern and specify a role who can access. b. role_hierarchy: here the hierarchical structure of role, for the below example an Admin user(ROLE_ADMIN) have roles ROLE_USER,ROLE_NEWS_AUTHOR. So he can access all pages of a USER and NEWS_AUTHOR.Whatever the hierarchy you can give.

    access_control:
            - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }/login any one can access this pattern
            - { path: ^/admin/, roles: ROLE_ADMIN }//block all pattern /admin/anything*
            - { path: ^/news/, roles: ROLE_NEWS_AUTHOR } //block all pattern /news/anything*
    role_hierarchy:
            ROLE_ADMIN: [ROLE_USER,ROLE_NEWS_AUTHOR]
    

    In your controller you can check the roles,

    if(TRUE ===$this->get('security.context')->isGranted('ROLE_ADMIN') )
    {
         // do something related to ADMIN
    }
    else if(TRUE ===$this->get('security.context')->isGranted('ROLE_NEWS_AUTHOR') )
    {
        // do something related to News Editor
    }
    

    Hope this helps you . HAppy coding.