Skip to content

Instantly share code, notes, and snippets.

@simonjodet
Created October 21, 2012 16:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save simonjodet/3927516 to your computer and use it in GitHub Desktop.
Save simonjodet/3927516 to your computer and use it in GitHub Desktop.
Silex automatic post-registration user authentication
<?php
$app['security.firewalls'] = array(
'user_firewall' => array(
'pattern' => new \Application\UserRequestMatcher($app['request']),
'form' => array('login_path' => '/login', 'check_path' => '/authenticate'),
'logout' => array('logout_path' => '/logout'),
'users' => $app->share(function () use ($app)
{
return new \Application\UserProvider($app);
}),
),
);
//...
$app->post(
'/register',
function (\Silex\Application $app)
{
$form->bind($app['request']);
$data = $form->getData();
$UserModel = new \Application\UserModel($app);
$UserModel->create($data);
$User = new \Symfony\Component\Security\Core\User\User($data['username'], $data['password'], array('ROLE_USER'));
$app['security']->setToken(new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($User, $User->getPassword(), 'user_firewall', array('ROLE_USER')));
return $app->redirect('/');
}
);
@swarajban
Copy link

thanks so much for this, I have been looking everywhere trying to find out how to do this

@elbahek
Copy link

elbahek commented May 8, 2016

thank you!

@artshevtsov
Copy link

This way works for Symfony 2.6.x - Symfony 3.0.x

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use YourNameSpace\UserBundle\Entity\User;

class LoginController extends Controller{

    public function registerAction() {    
        $user = //Handle getting or creating the user entity likely with a posted form
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        $this->get('session')->set('_security_main', serialize($token));
    }
}

@PYuen1029
Copy link

Thanks a bunch for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment