gpt4 book ai didi

symfony2 : check isGranted for a route

转载 作者:行者123 更新时间:2023-12-04 17:51:27 25 4
gpt4 key购买 nike

假设有某些路由字符串,例如受防火墙保护的“/path/index.html”,如何检查当前用户是否能够访问它?

提前致谢!

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

就像是:

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

最佳答案

此答案基于您的评论:
您应该获得访问该路由所需的角色。您需要访问 security.access_map服务是私有(private)的。所以它必须直接注入(inject)。例如:你可以创建一个 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']

现在在您的 Controller 中使用该服务来获取路径的角色并根据这些角色和 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 : check isGranted for a route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com