If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.
After registration, let’s log the user in automatically. Create a private function called authenticateUser inside RegisterController. Normally, authentication happens automatically, but we can also trigger it manually:
// src/Yoda/UserBundle/Entity/Controller/RegisterController.php
// ...
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
private function authenticateUser(User $user)
{
$providerKey = 'secured_area'; // your firewall name
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->container->get('security.context')->setToken($token);
}
This code might look strange, and I don’t want you to worry about it too much. The basic idea is that we create a token, which holds details about the user, and then pass this into Symfony’s security system.
Call this method right after registration:
// src/Yoda/UserBundle/Entity/Controller/RegisterController.php
// ...
if ($form->isValid()) {
// .. code that saves the user, sets the flash message
$this->authenticateUser($user);
$url = $this->generateUrl('event');
return $this->redirect($url);
}
Try it out! After registration, we’re redirected back to the homepage. But if you check the web debug toolbar, you’ll see that we’re also authenticated as Padmé. Sweet!
Thanks! You're absolutely right: though the old way will still work until Symfony 3.0 (but you'll start to see these pesky deprecation warnings). The above code will remove those warnings.
Cheers!
// composer.json
{
"require": {
"php": ">=5.3.3",
"symfony/symfony": "~2.4", // v2.4.2
"doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
"doctrine/doctrine-bundle": "~1.2", // v1.2.0
"twig/extensions": "~1.0", // v1.0.1
"symfony/assetic-bundle": "~2.3", // v2.3.0
"symfony/swiftmailer-bundle": "~2.3", // v2.3.5
"symfony/monolog-bundle": "~2.4", // v2.5.0
"sensio/distribution-bundle": "~2.3", // v2.3.4
"sensio/framework-extra-bundle": "~3.0", // v3.0.0
"sensio/generator-bundle": "~2.3", // v2.3.4
"incenteev/composer-parameter-handler": "~2.0", // v2.1.0
"doctrine/doctrine-fixtures-bundle": "~2.2.0", // v2.2.0
"ircmaxell/password-compat": "~1.0.3", // 1.0.3
"phpunit/phpunit": "~4.1" // 4.1.0
}
}
Since symfony 2.6, the code in the <strong>authenticateUser</strong> method should be:
Read more in this announcement http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements.