Setting Symfony2 security.context User data after

2020-07-22 17:39发布

Using Symfony2 I want to augment the security.content user after login with information obtained after login.

So in the login success code I do the following in AccountController:

$user = $this->get('security.context')->getToken()->getUser();

// Get everything we'll ever need for this user
$user->fillDetails($this, $this->container);

$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());

// Give it to the security context
$this->container->get('security.context')->setToken($token);

return $this->redirect($this->generateUrl('AccountBundle_homepage'));

If I immediately retrieve the user again after calling setToken() this information that is set in the User object in fillDetails() is still present.

However in the controller action for AccountBundle_homepage when I get the user using

$user = $this->get('security.context')->getToken()->getUser();

The extra information I set in fillDetails() is no longer there, or 0.

Any help appreciated.

标签: php symfony
1条回答
【Aperson】
2楼-- · 2020-07-22 17:54

The security context creates a token on each request, that means you can't modify a token, redirect the user and expect getting data set on the previous token. If you don't persist your user, it won't work. The user is reloaded on each request too.

You can find more information about the token here: http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html#the-token

查看更多
登录 后发表回答