Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-Login via URL with symfony2

I'm trying to do an auto login with symfony2 and a special kind of url. Just like described here.

But when I use the symfony2 debug toolbar, I notice that it says: "Not authenticated". But I have a session, I have a user object and it all seems to work just fine. Why is the debug toolbar saying this?

And is there something wrong with the method zadbuchy is describing? I'm using symfony 2.1.6.

Edit: I know that this may not the 'securest' way to login (Thanks to @Bart for the discussion), but I'm curious why symfony2 doesn't recognize the login correctly.

My code looks like this:

$firewall = "support_secured_area";
$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$this->get('security.context')->setToken($token);
$session = $this->get('session');
$session->set('_security_'.$firewall, serialize($token));

// Fire the login event (Suggestion from the answer, but unfortunately it doesn't work :( ).
$event = new InteractiveLoginEvent($this->getRequest(), $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
like image 660
Augunrik Avatar asked Mar 09 '13 14:03

Augunrik


2 Answers

You need the InteractiveLoginEvent to happen for the user to be logged in.

// Here, "public" is the name of the firewall in your security.yml
$token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles());
$this->get("security.context")->setToken($token);

// Fire the login event
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
like image 159
james_t Avatar answered Sep 28 '22 06:09

james_t


$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$this->get('security.context')->setToken($token);
$session = $this->get('session');
$session->set('_security_'.$firewall, serialize($token));

I applied above solution in a couple of our projects. One worked but another did not.

The final solution is using security_context_name instead of firewall_name in below line. Then it worked on every project.

$session->set('_security_'.$security_context_name, serialize($token));

Thanks for one of my colleagues pointing it out for me.

like image 41
Ycolin Avatar answered Sep 28 '22 06:09

Ycolin