2

我想在 loginSuccess 发生后根据取决于用户行为的参数为用户设置一些角色。

我看了看,看起来角色存储在可通过容器访问的 security.content.token 中:

$this->container->get('security.context')->getToken()

我可以看到角色存储在这个令牌中(在我的例子中是FacebookUserTokenfrom FOSFacebookBundle

我的另一个要求是我不能设置Roles和注销用户,它必须在同一个会话中。

那可能吗?

4

1 回答 1

5

我发现了这个问题:Get security token for non-logged user with Symfony

这帮助我认为我可以设置一个新的安全令牌(而不是尝试更新现有角色中的角色)。我的用户的角色没有存储在 User 表中,所以它是有意义的。

public function strangeAction()
{
    // Get your User, however you normally get it
    $user = $userRepository->find($id);

    // Save the original token in the session (just in case I need to reverse it)
    $originalToken = $this->get("security.context")->getToken();
    $this->getRequest()->getSession()->set('original.security.token', $originalToken);

    // Create my new custom token (loading the roles of the user)
    $token = new UsernamePasswordToken($user, null, "main", $user->getRolesMagically());

    // Update the security context with the new token
    $this->get("security.context")->setToken($token);

    // Now you have access to isGranted()
    if ($this->get("security.context")->isGranted("ROLE_SOMETHING"))
}

我对这个解决方案充满信心,但如果可能的话,我想要更多的输入。

IE。为什么我不应该这样做?

于 2013-02-27T00:41:44.877 回答