This tutorial has a new version, check it out!

Automatically Authenticating after Registration

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

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


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

What PHP libraries does this tutorial use?

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