【问题标题】:symfony2: check user permission with isGrantedsymfony2:使用 isGranted 检查用户权限
【发布时间】:2015-09-03 02:44:28
【问题描述】:

在课堂上 据说 vendor\friendsofsymfony\user-bundle\Model\User.php

/**
 * Never use this to check if this user has access to anything!
 *
 * Use the SecurityContext, or an implementation of AccessDecisionManager
 * instead, e.g.
 *
 *         $securityContext->isGranted('ROLE_USER');
 *
 * @param string $role
 *
 * @return boolean
 */
public function hasRole($role)
{
    return in_array(strtoupper($role), $this->getRoles(), true);
}

但 isGranted 返回实际用户的角色

        $data = $form->getData();
        $user = new User();
        $user->setUsername($data->getUsername());
        $user->setExpiresAt($data->getExpiresAt());
        $user->setName($data->getName());
        $user->setPassword($data->getPassword());
        $user->setEmail($data->getEmail());
        $user->setCredentialsExpired($data->isCredentialsExpired());
        $user->setRoles(array('ROLE_NEW'));
        $em->persist($user);
        $em->flush();
        // return false
        var_dump(
        $this->get('security.context')>isGranted('ROLE_NEW',$user));

如何检查特定用户的“isGranted”?

【问题讨论】:

    标签: symfony symfony-2.7


    【解决方案1】:

    简单地说:

    // $specific_user = get specific user from db.
    if (in_array('ROLE_SPECIFIC_ROLE', $specific_user->getRoles()))
    {
        // Make specific operation on specific user
    }
    

    【讨论】:

    • 在 User.php 类中,它说 /** * 永远不要用它来检查这个用户是否可以访问任何东西! * * 使用 SecurityContext,或 AccessDecisionManager * 的实现,例如* * $securityContext->isGranted('ROLE_USER'); *
    • 它不用于访问任何东西,您说要检查不是实际用户。安全上下文仅用于实际用户。如果你想允许特定用户访问你怎么做?只需简单地,您必须为他添加角色$user->addRole('ROLE_EDITOR'),并检查实际用户是否有权访问资源$this->get('security.authorization_checker')-isGranted('ROLE_EDITOR') 的安全上下文。
    【解决方案2】:

    您使用的是哪个版本?在最新版本中,您必须这样做:

     if ($this->get('security.authorization_checker')-isGranted('ROLE_NEW'))
    

    【讨论】:

    • 用“authorization_checker”测试也不起作用。
    • 正确的语法是:if ($this->get('security.authorization_checker')->isGranted('ROLE_NEW')) 无法更正答案,因为编辑需要至少 6 个字符。但这个版本适合我。
    【解决方案3】:

    编辑:我可能误读了您的问题。如果要检查特定用户的权限,请参见此处:Check if a role is granted for a specific user in Symfony2 ACL


    原答案

    您应该首先使用 FOSUserBundle 提供的UserManager 获取要检查的特定用户的实例。然后您可以检查该特定用户的 isGranted。

    您可以使用,例如:

    $userManager = $this->get('fos_user.user_manager');
    $user = $userManager->findUserByUsername('foobar'));
    

    source 中,您可能会找到几种查找用户的方法,包括通用的findUserBy()

    【讨论】:

    • 我已经有了用户的实例 $user = new User();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 2013-05-04
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多