假设有某些路线字符串,如" /path/index.html"受防火墙保护,如何判断当前用户是否能够访问它?
提前致谢!
对不起,我应该更明确一点:我有一系列路由名称,我构建了一个菜单。许多具有不同角色的用户可以使用此菜单访问页面。目的是在此菜单中仅显示特定用户的可访问权限。
类似的东西:
'security_context'->'user'->isGranted('/path/index.html')
答案 0 :(得分:5)
这个答案基于您的意见:
您应该获得访问该路由所需的角色。您需要访问私有的security.access_map
服务。因此必须直接注入.eg:您可以创建这样的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
}
}
答案 1 :(得分:0)
您可以使用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(...);
}
...
}
}