How to implement remember me programatically in symfony2?
Asked Answered
A

4

7

I have implemented a login function programmatically.

This code is following:

$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
$this->get('security.context')->setToken($token);

$event = new InteractiveLoginEvent($this->getRequest(),$token);
$this->get('event_dispatcher')->dispatch('security.interactive_login', $event);

After this, how do I implement remember me ?

(I know how to use form, but I want to implement remember me programmatically. )

please help...

Adorn answered 3/8, 2013 at 12:22 Comment(1)
You might check this question for a general picture.Redingote
C
9

Try to use RememberMeToken

$key = $this->getParameter('secret'); // your security key from parameters.yml

$token = new RememberMeToken($user, 'main', $key); 
$this->get('security.context')->setToken($token);
Clementeclementi answered 15/8, 2013 at 12:23 Comment(1)
I'm trying to make a facebook login. This log me in, but does not create a cookie. $token = new RememberMeToken($user, 'default', $this->getParameter('secret')); $this->get('security.token_storage')->setToken($token); In my security.yml: security: firewalls: default: remember_me: key: '%secret%' lifetime: 31536000 always_remember_me: trueLindane
J
1

I had the same problem.you should use RememberMeToken instead of UsernamePasswordToken.

The class parameters are very similar to UsernamePasswordToken so I don't go into details.

Jinny answered 14/8, 2013 at 22:26 Comment(0)
S
0

You can create a cookie with an unique ID. Then store this cookie in a database and check this database whenever a new visitor visits the site. In case you have your users stored in a database it would be best to make an extra column to store this information. Have a look at FOSUserBundle by the way.

Shirt answered 3/8, 2013 at 17:42 Comment(0)
S
0

I used the same method as forgottenbas suggested, but got an error. I had to use $this->container (Symfony2):

$key = $this->container->getParameter('secret');

$token = new RememberMeToken($user, 'user_area', $key); 
$this->get('security.context')->setToken($token);

$user is an instance of my User class and 'user_area' is the name of my firewall.

Singultus answered 22/2, 2014 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.