4

我有一个控制器,它应该通过一个简单的表单添加用户,但我无法让用户进行手动身份验证。

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken    

public function addAction($user)
    {
           $token =new UsernamePasswordToken(
                    $user->getUsername(),
                    $user->getPassword(),
                    'secured_area',
                   $user->getRoles()
                    );

           $this->get('security.context')->setToken($token);
           // as suggested in some other answers

           $request->getSession()->set('_security_secured_area', serialize($token));
           // as suggested in http://techblog.zabuchy.net/2012/manually-authenticate-symfony-2-user/

            return $this->redirect($this->generateUrl('acme_project_secure_show' )
                    );
        }
    }

重定向到安全路由有效,但是由于身份验证设置不$this->getUser()正确,该 方法返回 null ...$user= $this->get('security.context')->getToken();$user= $this->get('security.context')->getToken()->getUser();$this->getUser()

4

3 回答 3

6

问题已解决 - 缺少两点:1) 有必要InteractiveLoginEvent为链接发送 -thanks mpm 2) 此控制器的路由不在secured_area防火墙下 - 谢谢 Florian ;)

于 2013-01-29T22:43:47.153 回答
0

你可以试试这个

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken

$token = new UsernamePasswordToken($user, $user->getPassword(), "firewallname", $user->getRoles());
于 2013-01-25T00:56:40.903 回答
-1

正如@user19340357 所说,您可以手动实例化令牌。

他忘记说的是你应该在安全上下文中设置它:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken

$token = new UsernamePasswordToken($user, $user->getPassword(), "firewallname", $user->getRoles());
$securityContext = $this->container->get('security.context'); // do it your way
$securityContext->setToken($token);
于 2013-01-25T09:19:40.143 回答