繁体   English   中英

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

[英]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
}

SecurityContext将在Symfony 3.0弃用

Symfony 2.6之前,您将使用SecurityContext
Symfony 3.0中将弃用SecurityContext以支持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安全

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM