Symfony2 authentication automatically on Controller or elsewhere [duplicate] - php

We're building a business app from the ground up in Symfony 2, and I've run into a bit of a snag with the user registration flow: after the user creates an account, they should be automatically logged in with those credentials, instead of being immediately forced to provide their credentials again.
Anyone had any experience with this, or able to point me in the right direction?

Symfony 4.0
This process hasn't changed from Symfony 3 to 4 but here is an example using the newly recommended AbstractController. Both the security.token_storage and the session services are registered in the parent getSubscribedServices method so you don't have to add those in your controller.
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use YourNameSpace\UserBundle\Entity\User;
class LoginController extends AbstractController{
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->container->get('security.token_storage')->setToken($token);
$this->container->get('session')->set('_security_main', serialize($token));
// The user is now logged in, you can redirect or do whatever.
}
}
Symfony 2.6.x - Symfony 3.0.x
As of Symfony 2.6 security.context is deprecated in favor of security.token_storage. The controller can now simply be:
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));
}
}
While this is deprecated you can still use security.context as it has been made to be backward compatible. Just be ready to update it for Symfony 3.
You can read more about the 2.6 changes for security here: https://github.com/symfony/symfony/blob/2.6/UPGRADE-2.6.md
Symfony 2.3.x
To accomplish this in Symfony 2.3 you can no longer just set the token in the security context. You also need to save the token to the session.
Assuming a security file with a firewall like:
// app/config/security.yml
security:
firewalls:
main:
//firewall settings here
And a controller action similar to:
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.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
//Now you can redirect where ever you need and the user will be logged in
}
}
For the token creation you will want to create a UsernamePasswordToken. This accepts 4 parameters: User Entity, User Credentials, Firewall Name, User Roles. You don't need to provide the user credentials for the token to be valid.
I'm not 100% sure that setting the token on the security.context is necessary if you are just going to redirect right away. But it doesn't seem to hurt so I have left it.
Then the important part, setting the session variable. The variables naming convention is _security_ followed by your firewall name, in this case main making _security_main.

Figured this one out, finally.
After user registration, you should have access to an object instanceof whatever you've set as your user entity in your provider configuration. The solution is to create a new token with that user entity and pass it into the security context. Here's an example based on my setup:
RegistrationController.php:
$token = new UsernamePasswordToken($userEntity, null, 'main', array('ROLE_USER'));
$this->get('security.context')->setToken($token);
Where main is the name of the firewall for your application (thanks, #Joe). That's really all there is to it; the system now considers your user fully logged in as the user they've just created.
EDIT: Per #Miquel's comment, I've updated the controller code sample to include a sensible default role for a new user (though obviously this can be adjusted according to your application's specific needs).

If you have a UserInterface object (and that should be the case most of the time) you might want to use the getRoles function that it implements for the last argument.
So if you create a function logUser, it should looks like that:
public function logUser(UserInterface $user) {
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->container->get('security.context')->setToken($token);
}

I'm using Symfony 2.2 and my experience was slightly different than Problematic's, so this is a combined version of all the info from this question plus some of my own.
I think Joe is wrong about the value of $providerKey, the third parameter to the UsernamePasswordToken constructor. It's supposed to be the key of an authentication (not user) provider. It's used by the authentication system to distinguish between tokens created for different providers. Any provider which descends from UserAuthenticationProvider will only authenticate tokens whose provider key matches its own. For example, the UsernamePasswordFormAuthenticationListener sets the key of the token it creates to match that of its corresponding DaoAuthenticationProvider. That lets a single firewall have multiple username+password providers without them stepping on each other. We therefore need to choose a key that won't conflict with any other providers. I use 'new_user'.
I have a few systems in other parts of my application that depend on the authentication success event, and that isn't fired by just setting the token on the context. I had to get the EventDispatcher from the container and fire the event manually. I decided against also firing an interactive login event because we're authenticating the user implicitly, not in response to an explicit login request.
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
$user = // get a Symfony user instance somehow
$token = new UsernamePasswordToken(
$user, null, 'new_user', $user->getRoles() );
$this->get( 'security.context' )->setToken( $token );
$this->get( 'event_dispatcher' )->dispatch(
AuthenticationEvents::AUTHENTICATION_SUCCESS,
new AuthenticationEvent( $token ) );
Note that use of $this->get( .. ) assumes the snippet is in a controller method. If you're using the code somewhere else you'll have to change those to call ContainerInterface::get( ... ) in a way appropriate to the environment. As it happens my user entities implement UserInterface so I can use them directly with the token. If yours don't you'll have to find a way to convert them to UserInterface instances.
That code works, but I feel like it's hacking around Symfony's authentication architecture rather than working with it. It would probably be more correct to implement a new authentication provider with its own token class rather than hijacking the UsernamePasswordToken. Also, using a proper provider would mean that the events were handled for you.

With Symfony 4.4, you can simply do the following in your controller method (see from the Symfony documentation: https://symfony.com/doc/current/security/guard_authentication.html#manually-authenticating-a-user):
// src/Controller/RegistrationController.php
// ...
use App\Security\LoginFormAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
class RegistrationController extends AbstractController
{
public function register(LoginFormAuthenticator $authenticator, GuardAuthenticatorHandler $guardHandler, Request $request)
{
// ...
// after validating the user and saving them to the database
// authenticate the user and use onAuthenticationSuccess on the authenticator
return $guardHandler->authenticateUserAndHandleSuccess(
$user, // the User object you just created
$request,
$authenticator, // authenticator whose onAuthenticationSuccess you want to use
'main' // the name of your firewall in security.yaml
);
}
}
One important thing, make sure your firewall is not set to lazy. If it is, the token will never be stored in the session and you will never get logged in.
firewalls:
main:
anonymous: ~ # this and not 'lazy'

In case anyone has the same follow-on question which kept me coming back to here:
Calling
$this->container->get('security.context')->setToken($token);
only effects the current security.context for the route used.
I.e. you can only log in a user from a url within the firewall's control.
(Add an exception for the route if needed - IS_AUTHENTICATED_ANONYMOUSLY)

As Problematic here already mentioned, this elusive $providerKey parameter is in reality nothing more than the name of your firewall rule, 'foobar' in the case of the example below.
firewalls:
foobar:
pattern: /foo/

I tried all the answers here and none worked. The only way I could authenticate my users on a controller is by making a subrequest and then redirecting. Here is my code, I'm using silex but you can easily adapt it to symfony2:
$subRequest = Request::create($app['url_generator']->generate('login_check'), 'POST', array('_username' => $email, '_password' => $password, $request->cookies->all(), array(), $request->server->all());
$response = $app->handle($subRequest, HttpKernelInterface::MASTER_REQUEST, false);
return $app->redirect($app['url_generator']->generate('curriculos.editar'));

On Symfony version 2.8.11 (probably working for older and newer versions), if you use FOSUserBundle simply do this :
try {
$this->container->get('fos_user.security.login_manager')->loginUser(
$this->container->getParameter('fos_user.firewall_name'), $user, null);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
No need to dispatch event as I've seen in other solutions.
inpired from FOS\UserBundle\Controller\RegistrationController::authenticateUser
(from composer.json FOSUserBundle version : "friendsofsymfony/user-bundle": "~1.3")

Related

Add a constraint on the Symfony login form

I've encountered a new issue on my Symfony application and I cannot find anything to help me.
In my database, a user has an activation_token field.
When the user creates his account on my website, it generates a random token that will be used to validate his account. It will send him an email with the token in order to verify/activate his account and when he will click on it, it will set the activation_token field to null.
Creating the account works. Sending the email works. Validating the account works. I only have 1 issue.
I'd like to add a constraint that when the activation_token field is not null, the user won't be able to log in. In short, the user will need to validate his account at first in order to be able to log in. But I have no clue how to add a constraint like that.
Currently, I can log in even if I didn't validate my account and that's exactly what I want to prevent.
I haven't created a custom login form in PHP, I'm using the Security bundle from Symfony. Here we have a screenshot of my security.yaml file.
I don't know if it's possible to add a constraint with the Security bundle or not.
Expanding on Cerad's comment to the question:
If you are using Symfony >= 4.4 you can write a custom UserChecker. From the documentation:
<?php
namespace App\Security;
use App\Entity\User as AppUser;
use App\Exception\AccountDeletedException;
use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
if (!$user instanceof AppUser) {
return;
}
// this is your custom check:
if (null !== $user->getActivationToken()) {
throw new CustomUserMessageAccountStatusException('Please validate your account first, before logging in.');
}
}
public function checkPostAuth(UserInterface $user)
{
// nothing to check here.
return;
}
}
Add the user checker to your security configuration like this:
# config/packages/security.yaml
# ...
security:
firewalls:
main:
pattern: ^/
user_checker: App\Security\UserChecker
For version before Symfony 4.1
Instead of having your User Entity implementing the basic UserInterface, you can implement AdvancedUserInterface which contains more functions usefull for activating/deactivating user, locking user, expiring user etc
Here is the link of the documentation page: https://symfony.com/doc/4.0/security/entity_provider.html#forbid-inactive-users-advanceduserinterface
In your case, you may need to add this kind of logic:
public function isEnabled()
{
return null === $this->validationToken;
}

Laravel cookies comes with encryption, why?

I got the following serivce provider:
class CartServiceProvider extends ServiceProvider {
public function boot() {
}
public function register() {
$this->app->singleton(\Alexxosipov\Cart\Cart::class, function($app) {
return new \Alexxosipov\Cart\Cart($app['request']);
});
}
}
And my Cart class, where I got this:
$this->id = (request()->cookie('cart_id')) ? request()->cookie('cart_id') : false;
But request()->cookie('cart_id') returns encrypted string. If I will do it in any controller, it works fine. Why? What should I do to use it in Cart class?Laravel 5.5
The sequences of Laravel bootstrapping a request is this (v5.6): (CMIIW)
index.php is called
\Illuminate\Foundation\Application created
HttpKernel registered. This register your middlewares
Console Kernel registered. This defines console commands
Exception Handler registered. This defines exception handlers
HttpKernel instantiated. This instantiate all middlewares, plus boot/register all your service providers
Create global request instance. Pass it to HttpKernel to handle incoming request.
Middleware EncryptCookies called, cookies decrypted
Sending request to other middlewares to process
Send request to router, router dispatch to controller
...
Before sending response to browser, cookies encrypted back in EncryptCookies
Cookie is remained encrypted in Step 1 - Step 7. Your CartServiceProvider is trying to obtain a cookie that is yet to be decrypted at Step 6, which is not possible. Consider either
Decrypt the cookie by yourself (using just decrypt), or
Make a middleware to instantiate the cart after EncryptCookies. It's a little bit too early to instantiate cart at the bootstrapping service providers phase.
Edit: Add singleton suggestion
I think you could do this:
Create a new method named loadCartFromRequest($request) in your Cart::class. This method help you load a cart instance from request during the middleware phase.
In your CartServiceProvider, you register a singleton of Cart::class as usual, but no need to read the request here.
Create a middleware, called CartMiddleware. This middleware call app(Cart::class)->loadCartFromRequest($request).
Then at any other places that you need the cart instance, you can access your cart model from app(Cart::class).
I hope I understand your requirement correctly :)
Why? Cookie encryption protects data stored in the client's browser.
The How: Laravel uses the EncryptCookies middleware, this middleware would not yet be processed when your service provider is registered but would be processed for the controller since middlewares are in the routing stack before the request is passed to the controller.
Since I don't know about your cart class and its logic, I can't really recommend what you should do. Perhaps you need to think about when you are passing the Request object to your class.

Protecting controller actions and routes in Symfony

Official documentation on Symfony pages suggest using ROLE_ADMIN (example) attribute in the ACL call
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
my question is if it is possible to use ACL call without the ROLE_ prefix.
The issue is that we have multiple systems without ROLES but with permissions as "USER.CREATE" or "USER_CREATE" which would protect the route POST /user/create and action Create() in UserController.
The best solution would be to have a Voter which would call the ACL as
$objectName = 'USER';
$action = 'CREATE';
$this->denyAccessUnlessGranted($objectName. '_'. $action, null, 'Unable to access this page!');
But this does not work because everything relays on ROLE_ prefix.
Did anyone tried to achieve something like this?
IIRC, ROLE is mandatory prefix in symfony role voter and I do not think it can be avoided (it is hardcoded) but you can create your own voters and add logic you need there, you can read more here:
https://symfony.com/doc/current/security/voters.html
Also a great tutoral for voters:
https://stovepipe.systems/post/symfony-security-roles-vs-voters

Additional security checks on Symfony login

I'm using symfony 2.5 and I've come across a roadblock.
I am using SecurityContext as per symfony documentation in order to authenticate users. Specifically I currently have:
$securityContext = $this->container->get('security.context');
# If authenticated through Symfony
if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY'))
{
return $this->redirect($this->generateUrl('accounts_dashboard'), 301);
}
.....
This works well but this application registers users from several locations and at the time we didn't control duplicate registrations. This means we have multiple entries for the same email address.
Because of this, when someone tries to login and there are several accounts under the same email address the login procedure fails because it is selecting the wrong account.
I have other fields in the database that I could use to match the correct accounts, like active status, last login IP or even the last login date. The issue I have is that I am uncertain how to create additional checks during login to validate that information properly.
What would be the correct approach without having to rework the entire login logistics so that I could do additional checks on the database for the provided email address before calling SecurityContext and the rest of the login procedure? Essentially I am just trying to do additional checks after the login for has been submitted to ensure the correct account is being selected instead of the first match in the database.
UserProvider should return user by username, nothing else, it should not do some heavy logic. I think you can try to create your own authenticator as explained here by implementing the SimpleFormAuthenticatorInterface interface.
You need to implement a custom UserProvider. Example:
<?php
namespace Acme\Security\Authorization;
use Symfony\Bridge\Doctrine\Security\User\EntityUserProvider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
class MyCustomEmailUserProvider extends EntityUserProvider
{
/**
* {#inheritdoc}
*/
public function loadUserByUsername($username)
{
//your code to get user by email goes here
// if you found User, you need to return it from this method, otherwise throw an exception
throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));
}
}
You don't have to extend EntityUserProvider, you may consider your own UserProviderInterface implementation.
Register it as a service (assuming security.my_custom_email_user_provider service name), add your required dependencies and then add it to security.yml:
providers:
main:
id: security.my_custom_email_user_provider
And then use this provider on your login form:
firewalls:
firewall_name:
form_login:
provider: main
Check out Cookbook article for additional information.

Automatic post-registration user authentication

We're building a business app from the ground up in Symfony 2, and I've run into a bit of a snag with the user registration flow: after the user creates an account, they should be automatically logged in with those credentials, instead of being immediately forced to provide their credentials again.
Anyone had any experience with this, or able to point me in the right direction?
Symfony 4.0
This process hasn't changed from Symfony 3 to 4 but here is an example using the newly recommended AbstractController. Both the security.token_storage and the session services are registered in the parent getSubscribedServices method so you don't have to add those in your controller.
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use YourNameSpace\UserBundle\Entity\User;
class LoginController extends AbstractController{
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->container->get('security.token_storage')->setToken($token);
$this->container->get('session')->set('_security_main', serialize($token));
// The user is now logged in, you can redirect or do whatever.
}
}
Symfony 2.6.x - Symfony 3.0.x
As of Symfony 2.6 security.context is deprecated in favor of security.token_storage. The controller can now simply be:
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));
}
}
While this is deprecated you can still use security.context as it has been made to be backward compatible. Just be ready to update it for Symfony 3.
You can read more about the 2.6 changes for security here: https://github.com/symfony/symfony/blob/2.6/UPGRADE-2.6.md
Symfony 2.3.x
To accomplish this in Symfony 2.3 you can no longer just set the token in the security context. You also need to save the token to the session.
Assuming a security file with a firewall like:
// app/config/security.yml
security:
firewalls:
main:
//firewall settings here
And a controller action similar to:
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.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
//Now you can redirect where ever you need and the user will be logged in
}
}
For the token creation you will want to create a UsernamePasswordToken. This accepts 4 parameters: User Entity, User Credentials, Firewall Name, User Roles. You don't need to provide the user credentials for the token to be valid.
I'm not 100% sure that setting the token on the security.context is necessary if you are just going to redirect right away. But it doesn't seem to hurt so I have left it.
Then the important part, setting the session variable. The variables naming convention is _security_ followed by your firewall name, in this case main making _security_main.
Figured this one out, finally.
After user registration, you should have access to an object instanceof whatever you've set as your user entity in your provider configuration. The solution is to create a new token with that user entity and pass it into the security context. Here's an example based on my setup:
RegistrationController.php:
$token = new UsernamePasswordToken($userEntity, null, 'main', array('ROLE_USER'));
$this->get('security.context')->setToken($token);
Where main is the name of the firewall for your application (thanks, #Joe). That's really all there is to it; the system now considers your user fully logged in as the user they've just created.
EDIT: Per #Miquel's comment, I've updated the controller code sample to include a sensible default role for a new user (though obviously this can be adjusted according to your application's specific needs).
If you have a UserInterface object (and that should be the case most of the time) you might want to use the getRoles function that it implements for the last argument.
So if you create a function logUser, it should looks like that:
public function logUser(UserInterface $user) {
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->container->get('security.context')->setToken($token);
}
I'm using Symfony 2.2 and my experience was slightly different than Problematic's, so this is a combined version of all the info from this question plus some of my own.
I think Joe is wrong about the value of $providerKey, the third parameter to the UsernamePasswordToken constructor. It's supposed to be the key of an authentication (not user) provider. It's used by the authentication system to distinguish between tokens created for different providers. Any provider which descends from UserAuthenticationProvider will only authenticate tokens whose provider key matches its own. For example, the UsernamePasswordFormAuthenticationListener sets the key of the token it creates to match that of its corresponding DaoAuthenticationProvider. That lets a single firewall have multiple username+password providers without them stepping on each other. We therefore need to choose a key that won't conflict with any other providers. I use 'new_user'.
I have a few systems in other parts of my application that depend on the authentication success event, and that isn't fired by just setting the token on the context. I had to get the EventDispatcher from the container and fire the event manually. I decided against also firing an interactive login event because we're authenticating the user implicitly, not in response to an explicit login request.
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
$user = // get a Symfony user instance somehow
$token = new UsernamePasswordToken(
$user, null, 'new_user', $user->getRoles() );
$this->get( 'security.context' )->setToken( $token );
$this->get( 'event_dispatcher' )->dispatch(
AuthenticationEvents::AUTHENTICATION_SUCCESS,
new AuthenticationEvent( $token ) );
Note that use of $this->get( .. ) assumes the snippet is in a controller method. If you're using the code somewhere else you'll have to change those to call ContainerInterface::get( ... ) in a way appropriate to the environment. As it happens my user entities implement UserInterface so I can use them directly with the token. If yours don't you'll have to find a way to convert them to UserInterface instances.
That code works, but I feel like it's hacking around Symfony's authentication architecture rather than working with it. It would probably be more correct to implement a new authentication provider with its own token class rather than hijacking the UsernamePasswordToken. Also, using a proper provider would mean that the events were handled for you.
With Symfony 4.4, you can simply do the following in your controller method (see from the Symfony documentation: https://symfony.com/doc/current/security/guard_authentication.html#manually-authenticating-a-user):
// src/Controller/RegistrationController.php
// ...
use App\Security\LoginFormAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
class RegistrationController extends AbstractController
{
public function register(LoginFormAuthenticator $authenticator, GuardAuthenticatorHandler $guardHandler, Request $request)
{
// ...
// after validating the user and saving them to the database
// authenticate the user and use onAuthenticationSuccess on the authenticator
return $guardHandler->authenticateUserAndHandleSuccess(
$user, // the User object you just created
$request,
$authenticator, // authenticator whose onAuthenticationSuccess you want to use
'main' // the name of your firewall in security.yaml
);
}
}
One important thing, make sure your firewall is not set to lazy. If it is, the token will never be stored in the session and you will never get logged in.
firewalls:
main:
anonymous: ~ # this and not 'lazy'
In case anyone has the same follow-on question which kept me coming back to here:
Calling
$this->container->get('security.context')->setToken($token);
only effects the current security.context for the route used.
I.e. you can only log in a user from a url within the firewall's control.
(Add an exception for the route if needed - IS_AUTHENTICATED_ANONYMOUSLY)
As Problematic here already mentioned, this elusive $providerKey parameter is in reality nothing more than the name of your firewall rule, 'foobar' in the case of the example below.
firewalls:
foobar:
pattern: /foo/
I tried all the answers here and none worked. The only way I could authenticate my users on a controller is by making a subrequest and then redirecting. Here is my code, I'm using silex but you can easily adapt it to symfony2:
$subRequest = Request::create($app['url_generator']->generate('login_check'), 'POST', array('_username' => $email, '_password' => $password, $request->cookies->all(), array(), $request->server->all());
$response = $app->handle($subRequest, HttpKernelInterface::MASTER_REQUEST, false);
return $app->redirect($app['url_generator']->generate('curriculos.editar'));
On Symfony version 2.8.11 (probably working for older and newer versions), if you use FOSUserBundle simply do this :
try {
$this->container->get('fos_user.security.login_manager')->loginUser(
$this->container->getParameter('fos_user.firewall_name'), $user, null);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
No need to dispatch event as I've seen in other solutions.
inpired from FOS\UserBundle\Controller\RegistrationController::authenticateUser
(from composer.json FOSUserBundle version : "friendsofsymfony/user-bundle": "~1.3")

Categories