有人可以解释一下如何在控制器中手动创建记住我的cookie吗?
我希望用户在按下“注册”后保持登录状态
按钮,之后无需使用凭据登录.
我试图手动创建一个cookie,但我猜的是cookie
值不正确,因此“记住我”的功能
不起作用.
设置了具有正确名称的cookie.我检查过了.
security.yml
security.yml记得我
security: firewalls: main: remember_me: lifetime: 86400 domain: ~ path: / key: myKey
这就是我现在所拥有的,即使设置了cookie,它也不起作用.
$um = $this->get('fos_user.user_manager'); $member = $um->createUser(); … Form stuff with bindRequest etc. $um->updatePassword($member); $um->updateUser($member); $providerKey = $this->container->getParameter('fos_user.firewall_name'); $securityKey = 'myKey'; $token = new RememberMeToken($member,$providerKey,$securityKey,$member->getRoles()); $this->container->get('security.context')->setToken($token); $redirectResponse = new RedirectResponse($url); $redirectResponse->headers->setCookie( new \Symfony\Component\HttpFoundation\Cookie( 'REMEMBERME',base64_encode(implode(':',array($member->getUsername(),$member->getPassword()))),time() + 60*60*24 ) ); return $redirectResponse;
更新:
我也尝试过使用
PersistentTokenBasedRememberMeServices类具有反射但它不起作用.一个cookie被设置但它不起作用
$token = $this->container->get('security.context')->getToken(); $providerKey = $this->container->getParameter('fos_user.firewall_name'); $securityKey = 'myKey'; $persistenService = new PersistentTokenBasedRememberMeServices(array($um),array('path' => '/','name' => 'REMEMBERME','domain' => null,'secure' => false,'httponly' => true,'lifetime' => 86400)); $persistenService->setTokenProvider(new InMemoryTokenProvider()); $method = new \ReflectionMethod('Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices','onLoginSuccess'); $method->setAccessible(true); $method->invoke($persistenService,$request,$redirectResponse,$token);
我正在使用Symfony v2.0.5和FOSUserBundle 1.0
更新2:
我尝试了第三种方式.与上述相同但没有反思:
$token = $this->container->get('security.context')->getToken(); $providerKey = $this->container->getParameter('fos_user.firewall_name'); $securityKey = 'myKey'; $persistenService = new PersistentTokenBasedRememberMeServices(array($um),'domain' => null,'lifetime' => 31536000,'always_remember_me' => true,'remember_me_parameter' => '_remember_me')); $persistenService->setTokenProvider(new InMemoryTokenProvider()); $persistenService->loginSuccess($request,$token);
解决方法
如果要直接设置记忆cookie,则必须使用以下格式:
base64_encode(<classname>:base64_encode(<username>):<expiry-timestamp>:<hash>)
哈希将在哪里:
sha256(<classname> . <username> . <expiry-timestamp> . <password> . <key>)
密钥是您在remember_me部分中输入安全性(.xml / .yml)的密钥.
这取自Symfony / Component / Security / Http / RememberMe / TokenBasedRememberMeService.PHP文件中的processAutoLoginCookie()方法.
这都是由同一个类中的generateCookieValue()方法完成的.
但是,我不建议直接使用这种方式,但是尝试查看是否可以调用TokenBasedRememberMeService :: onLoginSuccess()方法,该方法为您设置此cookie以使代码更加健壮和可移植.