1

在类 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”?

4

3 回答 3

1

简单地说:

// $specific_user = get specific user from db.
if (in_array('ROLE_SPECIFIC_ROLE', $specific_user->getRoles()))
{
    // Make specific operation on specific user
}
于 2015-09-02T18:44:28.880 回答
1

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

 if ($this->get('security.authorization_checker')-isGranted('ROLE_NEW'))
于 2015-09-02T17:23:31.673 回答
0

编辑:我可能误读了你的问题。如果要检查特定用户的权限,请参阅此处:检查是否为 Symfony2 ACL 中的特定用户授予角色


原始答案

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

例如,您可以使用:

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

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

于 2015-09-02T17:17:02.143 回答