【问题标题】:symfony2: check isGranted for a routesymfony2:检查 isGranted 的路由
【发布时间】:2014-07-29 12:51:16
【问题描述】:

假设某个路由字符串如“/path/index.html”被防火墙保护,如何判断当前用户是否可以访问?

提前致谢!

对不起,我应该更明确一点:我有一个路由名称数组,我构建了一个菜单。许多具有不同角色的用户可以使用此菜单访问页面。目的是仅在此菜单中为特定用户显示可访问的点赞。

类似:

'security_context'->'user'->isGranted('/path/index.html')

【问题讨论】:

标签: symfony


【解决方案1】:

此答案基于您的 cmets: 您应该获得访问该 route.to 所需的角色,您需要访问私有的 security.access_map 服务。因此必须直接注入它。例如:您可以创建一个 path_roles 服务,这样您可以获得特定路径的角色:

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;
    }
}

现在将其声明为服务:

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

现在在您的控制器中使用该服务来获取路径的角色并根据这些角色和 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
      }
  }

【讨论】:

  • 它只适用于像'/home'这样的路径,而不是像'homepage'这样的路由名称,对吧?如何修改它以使用路由?
  • @OlegAbrazhaev 你可以将RouterInterface注入到PathRoles服务中,然后使用$router->getRouteCollection()->get($routeName)->getPath()获取路径
【解决方案2】:

您可以使用security.access_control 配置选项:

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

或者只是在控制器中手动检查:

class SomeController extends Controller {
    public function indexAction() {
        if (!$this->get('security.context')->isGranted(...)) {
            throw new AccessDeniedException(...);
        }

        ...
    }
}

【讨论】:

  • 感谢您的回答。抱歉,我应该更明确一点:我有一组路线名称,并且我构造了菜单。许多具有不同角色的用户可以使用此菜单访问页面。目的是仅在此菜单中为特定用户显示可访问的点赞。
猜你喜欢
  • 1970-01-01
  • 2016-04-04
  • 2012-09-16
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
相关资源
最近更新 更多