Buy

Automatically Authenticating after Registration

UPGRADE! Check out the newest version of this tutorial

Automatically Authenticating after Registration

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 Symrony’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!

Leave a comment!

  • 2015-12-21 weaverryan

    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!

  • 2015-12-21 YoyoSan

    Since symfony 2.6, the code in the authenticateUser method should be:


    $providerKey = 'secured_area';
    $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());

    $this->container->get('security.token_storage')->setToken($token);

    Read more in this announcement http://symfony.com/blog/new-in....

  • 2015-07-09 weaverryan

    I see we were missing that use statement in the code block. I've just fixed that.

    Thanks!

  • 2015-07-09 guest

    use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;