如何以编程方式将角色分配给symfony4用户

时间:2018-04-06 21:30:49

标签: php symfony symfony4

我正在尝试创建一个以编程方式为当前用户分配特定ROLE的路由。这是我的尝试。

/**
 * @Route("/role/assign/{role}", name="role_assignment")
 */
public function assign($role)
{
    $session = $this->get('session');
    $firewallContext = 'main';
    $token = new UsernamePasswordToken(
        'admin',
        null,
        $firewallContext,
        array('ROLE_ADMIN')
    );
    $session->set('_security_'.$firewallContext, serialize($token));
    $session->save();
    $cookie = new Cookie($session->getName(), $session->getId());

    $response = new JsonResponse([
        'success' => 'true',
        'user' => $this->getUser(),
    ]);

    $response->headers->setCookie($cookie);

    return $response;
}

用户始终为空,但我希望他在页面刷新后成为“管理员”。

1 个答案:

答案 0 :(得分:1)

我强烈建议你不要在生产平台上做这些事情。您最好正确配置User Impersonation。它将为您省去手动完成所有这些工作的麻烦。

如果您真的,真的,想要通过这种方式尝试下面的代码:

SELECT document 
FROM originalTable o
WHERE exists 
(
   SELECT 1 
   FROM temporaryTable t
   WHERE t.id <> o.id AND t.key = o.key
)

如果您正在尝试对测试用例进行身份验证,可以查看我的回答here,其中显示了如何配置/** * @Route("/role/assign/{username}/{role}", name="role_assignment") * * @param \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $tokenStorage * * @return JsonResponse */ public function assign($username, $role, TokenStorageInterface $tokenStorage) { // NOTES: // 1. Make sure you are using the same User class as the one configured in `security.yml` // 2. Keep in mind the $username MUST exist and MUST have the role you are setting, // because the UserPasswordToken is reloaded from the session upon page refresh which triggers a check in the user provider and that will hit the database. In other words, if the user doesn't have `ROLE_ADMIN` you will most-likely get logged out or see "AccessDeniedException". // For more information check \Symfony\Component\Security\Core\User\UserProviderInterface::refreshUser. $user = new \Symfony\Component\Security\Core\User\User($username, null, array($role), true); // Create token $firewall = 'main'; // This MUST MATCH the name in your security.firewalls.->main<- or authentication WILL FAIL! $usernamePasswordToken = new UsernamePasswordToken($user, null, $firewall, $user->getRoles()); // You don't need to save the token via $session->save(). // You can directly use $tokenStorage, which will do that for you. $tokenStorage->setToken($usernamePasswordToken); // Pass authentication to client. return new JsonResponse(['success' => 'true', 'user' => $user]); } 可以作为任何具有您设置角色的用户进行身份验证(用户甚至不必存在于db)中。这对我来说在3.4上工作正常,所以它仍然适用于4.0。