我有一个管理面板,我已经为它定义了角色ROLE_ADMIN
。在我的 security.yml 文件中,我正在使用一种模式^/admin/*
因此/admin 下的每件事都需要 ROLE_ADMIN
.现在在我的应用程序的前端,我需要检查用户角色,如果角色ROLE_ADMIN
渲染一个文件,否则渲染另一个文件。此 url 不属于 security.yml 中定义的模式。
那么如何检查用户是管理员还是主页上的普通用户,这不属于 security.yml 中定义的模式?
使用^/
模式在整个应用程序上启用防火墙,允许匿名访问并使用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
}
SecurityContext 将在Symfony 3.0
中被弃用
在Symfony 2.6
之前,您将使用 SecurityContext
.
SecurityContext
将在Symfony 3.0
中被弃用,取而代之的是AuthorizationChecker
。
对于Symfony 2.6+
和Symfony 3.0
请使用AuthorizationChecker
。
Symfony 2.5(及以下版本(
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
Symfony 2.6(及以上版本(
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 2中的最佳实践,请看这里享受!
在Symfony 4及更高版本中,你应该使用如下代码,而不是使用 $this->get('security.authorization_checker'( 等服务:
$hasAccess = $this->isGranted('ROLE_ADMIN');
$this->denyAccessUnlessGranted('ROLE_ADMIN');
Symfony安全