symfony 3.3 programmatically login a user with remember me feature

不羁的心 提交于 2019-12-04 22:41:13

Here I had my own answer. First, login user with following snippet

    $user = new \AppBundle\Security\User\EndUser($id, $userKey, $username, $password, $salt, $roles);
    $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
    $this->container->get('security.token_storage')->setToken($token);
    $this->container->get('session')->set('_security_main', serialize($token));

Be aware that your own userProvider or EndUser maybe different from mine. Change the $user accordingly to make it work in your own situation.

Second, implement the remember me feature.

    $file   = sprintf("%s/config/security.yml", $this->container->getParameter('kernel.root_dir'));
    $parsed = Yaml::parse(file_get_contents($file));
    $options = $parsed['security']['firewalls']['main']['remember_me'];

    $endUserProvider = $this->container->get('AppBundle\Security\User\EndUserProvider');
    $secret = $providerKey = $this->container->getParameter('secret');
    $service = new TokenBasedRememberMeServices(array($endUserProvider), $secret, $providerKey, $options, null);
    $r = new \ReflectionMethod($service, 'onLoginSuccess');
    $r->setAccessible(true);
    $r->invoke($service, $request, $response, $token);

Some explanation here. Above code is firstly fetch remember me configuration for security.yml which is needed to initiate TokenBasedRememberMeServices instance. Then use the ReflectionMethod to overcome the accessible issue because method onLoginSuccess is originally protected.

This solution is tested under symfony 3.3.16. Hope this help others.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!