Description
Description
Before the new authenticator-based Security (5.1+), logging in programmatically an User required some boilerplate code:
// Here, "main" is the name of the firewall in your security.yaml
$token = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles());
$this->get("security.token_storage")->setToken($token);
// Fire the login event
// Logging the user in above the way we do it doesn't do this automatically
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
// Code adapted from https://stackoverflow.com/questions/9550079/how-to-programmatically-login-authenticate-a-user
With the new system, it is now easier to programmatically log in an User:
$response = $authenticatorManager->authenticateUser($user, $authenticator, $request);
Though one concept was lost: it is not possible anymore to say against which firewall the user should be authenticated.
I have a specific use case where it is problematic: in our app, we "upgrade" users from a stateless firewall (based on a query token) to the "main" firewall. As the first firewall has no session, authenticated is never retained with the new helper.
The current workaround I'm using, FYI:
$response = $authenticatorManager->authenticateUser($user, $authenticator, $request);
$token = $this->tokenStorage->getToken();
// We force storage of Token in Session, for "main" firewall,
// even if the current page is under "my_link_token" stateless firewall
$request->getSession()->set('_security_main', serialize($token));
Example
Ideally, we should have an "AuthenticatorManager" helper which knows about multiple firewalls, and we can pass firewall name as an extra parameter. It would also make for sense regarding authenticateRequest
I think, as right now User has to make sure the request matches the current firewall.