How to create and register new roles in Symfony2

I see from the official Symfony2 doc on Security that new roles can be defined in addition to the "classic" ones (for example, ROLE_USER, ROLE_ADMIN, etc.).

How to define new roles and register them in a Symfony2 application to create a hierarchy of roles in security.yml?

Sorry to bother you all! I think the answer is simple. Actually, it seems enough to start using the new role by running the name using ROLE _ . For example, you could say ROLE_NEWS_AUTHOR to allow only people with this role to embed news on the website.

Thanks.

+7
source share
1 answer

Of course, you can simply add any roles starting with ROLE_SOMEROLE. The security.yml file has two main parts: 1. Restrict access 2. Which member can access

but. access_control: which restricts the pattern and indicates the role that can be accessed. b. role_hierarchy: here is the hierarchical structure of the role, for the example below, the Admin user (ROLE_ADMIN) has the roles ROLE_USER, ROLE_NEWS_AUTHOR. This way, he can access all USER and NEWS_AUTHOR pages. Whatever hierarchy you could 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.

+13
source

All Articles