symfony2:检查 isGranted 以获取路线 [英] symfony2: check isGranted for a route

查看:20
本文介绍了symfony2:检查 isGranted 以获取路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

提前致谢!

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

I am sorry, I should have been more explicit: I have an array of route names and I construct a menu. A lot of users with different roles can access a page with this menu. The purpose is to show only accessible liks in this menu for a particular user.

类似于:

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

推荐答案

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

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

现在将其声明为服务:

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

现在在您的控制器中使用该服务来获取路径的角色并基于这些角色和 isGranted.i.e 构建您的菜单:

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

这篇关于symfony2:检查 isGranted 以获取路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆