Buy Access to Course
26.

Automatically Authenticating after Registration

Share this awesome video!

|

Keep on Learning!

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