symfony2: check isGranted for a route

后端 未结 2 1538
天涯浪人
天涯浪人 2020-12-11 06:51

supposed having certain route string like \"/path/index.html\" protected by firewall, how to chek whether current user is able to access it?

Thanks in advance!

相关标签:
2条回答
  • 2020-12-11 07:16

    This answer is based on your comments: You should get the roles needed to access that route.to that you need access to the security.access_map service which is private.so it has to be injected directly.e.g: you can create a path_roles service like such that you can get the roles for a certain path:

    namespace Acme\FooBundle;
    
    class PathRoles
    {
        protected $accessMap;
    
        public function __construct($accessMap)
        {
            $this->accessMap = $accessMap;
        }
    
        public function getRoles($path)
        { //$path is the path you want to check access to
    
            //build a request based on path to check access
            $request = Symfony\Component\HttpFoundation\Request::create($path, 'GET');
            list($roles, $channel) = $this->accessMap->getPatterns($request);//get access_control for this request
    
            return $roles;
        }
    }
    

    now declare it as a service:

    services:
        path_roles:
            class: 'Acme\FooBundle\PathRoles'
            arguments: ['@security.access_map']
    

    now use that service in your controller to get the roles for the path and construct your menu based on those roles and isGranted.i.e:

      //code from controller
      public function showAction(){
          //do stuff and get the link path for the menu,store it in $paths
          $finalPaths=array();
          foreach($paths as $path){
          $roles = $this->get('path_roles')->getRoles($path);
          foreach($roles as $role){
              $role = $role->getRole();//not sure if this is needed
              if($this->get('security.context')->isGranted($role)){
                  $finalPaths[] = $path;
                  break;
              }
          }
         //now construct your menu based on $finalPaths
          }
      }
    
    0 讨论(0)
  • 2020-12-11 07:22

    You could use security.access_control configuration option:

    securty:
        access_control:
            - { path: "^/path/index.html$", roles: ROLE_SOME_ROLE}
    

    Or simply check that manually from within your controller:

    class SomeController extends Controller {
        public function indexAction() {
            if (!$this->get('security.context')->isGranted(...)) {
                throw new AccessDeniedException(...);
            }
    
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题