使用Symfony2 Security以另一用户身份进行管理员登录


Admin login as another user with Symfony2 Security

我有一个系统,它有两个角色(管理员和用户)。使用Security Symfony2组件进行身份验证。管理员不知道用户密码。但他应该能够以用户身份登录到系统中。我有一个包含所有用户的网格,并希望添加类似"以该用户身份登录"的按钮。我该怎么做?

我试过了,但没有合适的:

$userRepo = $this->getDoctrine()->getRepository('FrameFoxBackEndBundle:User');
$this->get('security.context')->getToken()->setUser($userRepo->find(1));

为什么不使用内置的switch用户选项?

我使用以下代码:

// use Symfony'Component'Security'Core'Authentication'Token'UsernamePasswordToken
$entity = $userRepo->find(1);
// Authentication
// create the authentication token
$token = new UsernamePasswordToken(
    $entity,
    null,
    'user_db',
    $entity->getRoles());
// give it to the security context
$this->container->get('security.context')->setToken($token);

我会使用Symfony核心支持来实现这种方式。看看:http://symfony.com/doc/current/cookbook/security/impersonating_user.html.

您定义了一个允许切换用户的角色,以及url中一个允许您切换用户的参数。