问题描述
我有一个管理面板,我已经为它定义了一个角色 ROLE_ADMIN
.在我的 security.yml 文件中,我使用了一个模式 ^/admin/*
,所以/admin 下的每件事都需要 ROLE_ADMIN
.现在在我的应用程序的前端,我需要检查用户角色,如果角色是 ROLE_ADMIN
渲染一个文件,否则渲染另一个文件.此 url 不属于 security.yml 中定义的模式.
I have a admin panel and I have defined a role for it ROLE_ADMIN
. In my security.yml file I am using a pattern ^/admin/*
so every thing under /admin requires ROLE_ADMIN
. Now in frontend of my app I need to check user role and if role is ROLE_ADMIN
render one file and otherwise render another file. This url does not fall under the pattern defined in security.yml.
那么如何检查主页上的用户是管理员还是普通用户,不属于 security.yml 中定义的模式?
So how do I check whether the user is admin or a normal user on the homepage which does not fall under the pattern defined in security.yml ?
推荐答案
使用 ^/
模式在整个应用程序上启用防火墙,允许匿名访问并使用 access_control
限制访问:
Enable the firewall on the whole app using the ^/
pattern, permit anonymous access and use access_control
to restrict access:
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
服务来解决这个问题:
In Symfony 2.6, security.context
has been split into two separate services. Hence you need to use the security.authorization_checker
service to solve the problem:
if ($this->get('security.authorization_checker')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
这篇关于我如何检查 symfony2 中的用户角色是否不属于定义的 security.yml 模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!