[英]How do I check for user role in symfony2 for urls not falling under patterns defined security.yml?
我有一个管理面板,我为它定义了一个角色ROLE_ADMIN
。 在我的security.yml文件中,我使用的是模式^/admin/*
所以/ admin下的每个东西都需要ROLE_ADMIN
。 现在在我的应用程序的前端,我需要检查用户角色,如果角色是ROLE_ADMIN
渲染一个文件,否则渲染另一个文件。 此URL不属于security.yml中定义的模式。
那么如何在主页上检查用户是管理员还是普通用户,该用户不属于security.yml中定义的模式?
使用^/
pattern在整个应用程序上启用防火墙,允许匿名访问并使用access_control
来限制访问:
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
正如@itsmequinn建议的那样,使用安全上下文的isGranted()
方法:
if ($this->get('security.context')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
在Symfony 2.6中 , security.context
已拆分为两个单独的服务。 因此,您需要使用security.authorization_checker
服务来解决问题:
if ($this->get('security.authorization_checker')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
Symfony 3.0
弃用 在Symfony 2.6
之前,您将使用SecurityContext
。
在Symfony 3.0
中将弃用SecurityContext
以支持AuthorizationChecker
。
对于Symfony 2.6+
和Symfony 3.0
使用AuthorizationChecker
。
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
类似问题: 如何检查用户是否在控制器内登录Symfony2?
阅读更多文档: AuthorizationChecker
你是该页面的控制器吗? 如果是这样,请使用安全上下文的isGranted
方法: 控制器的访问控制
最简单的解决方案是注释。 而不是这个:
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
..试试用这个:
/**
* ...
* @Security("has_role('ROLE_ADMIN')")
*/
.. 要么 :
/**
* ...
* @Security("is_granted('POST_ADD', post)")
*/
public function addAction(Post $post){...}
在Symfony 4及更高版本中,您应该使用如下代码,而不是使用像$ this-> get('security.authorization_checker')这样的服务:
$hasAccess = $this->isGranted('ROLE_ADMIN');
$this->denyAccessUnlessGranted('ROLE_ADMIN');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.