简体   繁体   中英

User Role based routes in Symfony

I've got five types of roles in my Symfony project.

I want to create restrictions for each role, so that they will have access to specific routes. They will not be able to access others paths. I want to do this in an efficient way like Laravel uses middleware in the routes for access. Is there any way like this in Symfony ?

You could do that in different ways, and it depends on your Symfony version.

In the older Symfony versions, the most common way to restrict access to certain routes is adding into config/packages/security.yaml some parameters such as:

 access_control:
    - { path: '^/agent', roles: ROLE_AGENT }
    - { path: '^/profile', roles: ROLE_USER }
    - { path: '^/admin', roles: ROLE_ADMIN }
    - { path: '^/admin/statistics', roles: ROLE_SUPER_ADMIN }
    

Also, it's good practice to define the role hierarchy into the same file config/packages/security.yaml :

`role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN`

Hence, the users with a SUPER_ADMIN_ROLE will have access to routes restricted to ROLE_ADMIN.

However, my recommendation is if you've several parts to restrict define the general access roles into the config/packages/security.yaml file such as and define a role hierarchy as I said before:

 access_control:
    - { path: '^/admin', roles: ROLE_ADMIN }
    - { path: '^/profile', roles: ROLE_USER }

Then restrict the other routes using annotations thanks to SensioFrameworkExtraBundle , for example:

 use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

 /**
  * Require ROLE_ADMIN_SYSTEMS for *every* controller method in         this class.
  *
  * @IsGranted("ROLE_ADMIN_SYSTEMS")
  */

   public function YourFunction() { }

For more information look into official Symfony Docs that are very clear. Symfony Security official documentation

I hope this could help you, if you've any other doubts just tell me,

Kind regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM