如何检查symfony2中的用户角色,以查找不属于模式定义的security.yml的URL?

时间:2012-09-05 18:37:53

标签: php symfony

我有一个管理面板,我为其定义了一个角色ROLE_ADMIN。在我的security.yml文件中,我使用的是模式^/admin/*,因此/ admin下的所有内容都需要ROLE_ADMIN。现在在我的应用程序的前端,我需要检查用户角色,如果角色是ROLE_ADMIN渲染一个文件,否则渲染另一个文件。此网址不属于security.yml中定义的模式。

那么如何在主页上检查用户是管理员还是普通用户,该用户不属于security.yml中定义的模式?

5 个答案:

答案 0 :(得分:29)

使用^/模式在整个应用上启用防火墙,允许匿名访问并使用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
}

答案 1 :(得分:20)

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
}

类似问题:How to check if an user is logged in Symfony2 inside a controller?

在此处阅读更多文档:AuthorizationChecker

答案 2 :(得分:5)

您是否在该页面的控制器中?如果是,请使用安全上下文的isGranted方法:Access Controls for Controllers

答案 3 :(得分:1)

最简单的解决方案是注释。而不是:

    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){...}

您可以阅读有关Security annotations here的更多信息。注释是Symfony 2中的最佳实践here享受!

答案 4 :(得分:0)

Symfony 4及更高版本中,您应使用以下代码, 而不是使用$ this-> get('security.authorization_checker')这样的服务:

return this.props.outboundTrains.map((train, idx) => (
  <ListItem 
    key={idx}
    title={train.station}
  />
))

Symfony security

相关问题