Last active
June 21, 2024 08:44
-
-
Save azhararmar/0a952cf03b1cfbd2a5b059089b764491 to your computer and use it in GitHub Desktop.
Manually Authenticate User In Symfony
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; | |
// Manually authenticate user in controller | |
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); | |
$this->get('security.token_storage')->setToken($token); | |
$this->get('session')->set('_security_main', serialize($token)); |
If you use Symfony Guard for the authentication.
return $this->guardAuthenticatorHandler->authenticateUserAndHandleSuccess(
$user,
new Request(),
$this->emailPasswordAuthenticator,
self::FIREWALL_MAIN
);
Where $this->emailPasswordAuthenticator its your - AbstractGuardAuthenticator
Thank you so much @azhararmar
You pointed me in the right direction. Thank you very much!
This is how I did it in my Symfony 5 service:
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
// ....
public function __construct(
TokenStorageInterface $tokenStorage, SessionInterface $session
) {
$this->tokenStorage = $tokenStorage;
$this->session = $session;
}
public function login($username, $roles)
{
// ....
$token = new UsernamePasswordToken($username, null, 'main', $roles);
$this->tokenStorage->setToken($token);
$this->session->set('_security_main', serialize($token));
// ....
}
thanks @ZaneCEO This kinda worked for me but I then got an error in the Controller the user was redirecto to that tried to get the user with
$this->security->getUser()
To get this to work I changed the code a bit and now it works fine for me :
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$this->manager->persist($user);
$this->manager->flush();
$token = new PostAuthenticationToken(
$user,
'main', // firewall name in security.yaml
$user->getRoles()
);
$this->tokenStorage->setToken($token);
$this->session->set('_security_main', serialize($token));
return $this->redirectToRoute('dashboard');
Symfony 5.3
PHP 8.0
In Symfony 5.3 SessionInterface
is deprectaed, you can not inject it and should retrieve it from RequestStack
<?php
namespace App\Service\User;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
class Authenticate
{
private SessionInterface $session;
public function __construct(
private TokenStorageInterface $tokenStorage,
RequestStack $requestStack,
) {
$this->session = $requestStack->getSession();
}
public function login(UserInterface $user, string $firewallName = 'main'): void
{
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$this->tokenStorage->setToken($token);
$this->session->set('_security_main', serialize($token));
}
}
As an alternative for 5.3, this is working too :
<?php
namespace App\Security;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
class Authentication
{
public function __construct(
private AuthenticationManagerInterface $authenticationManager,
private TokenStorageInterface $tokenStorage,
)
{
}
public function login(UserInterface $user): void
{
$token = new UsernamePasswordToken($user, null, 'firewallName', $user->getRoles());
$authenticatedToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authenticatedToken);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, I am using Symfony 4... I just did, used this code, also I tried the procedure from the link of @warthy.
I can make an autorization, but after reload or next request, the token is lost.
Please any idea? Why authorization is not saved into session? Thank you
My authentication code:
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
$sess = $this->get('session')->set('_security_main', serialize($token));
// Fire the login event manually
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch("security.interactive_login", $event);
// dump($this->getUser()); exit;
this dump is returning User well, right after loginDump of real User entity giving into Token:
User {#444
-role: "user"
-name: ""
-surname: ""
-email: "asd@asd.sk"
-password: "54d5cb2d332dbdb4850293caae4559ce88b65163f1ea5d4e4b3ac49d772ded14"
-createdAt: DateTime @1545679179 {#442
date: 2018-12-24 19:19:39.0 UTC (+00:00)
}
-id: 43
-loginRole: UserLoginRole {#458
+__isInitialized__: false
-description: null
-id: "ROLE_BUYER"
…2
}
#roles: null
#salt: null
#groups: ArrayCollection {#521
-elements: []
}
}
Dump of the $this->getUser() right after authentification:
User {#444
-role: "user"
-name: ""
-surname: ""
-email: "asd@asd.sk"
-password: "54d5cb2d332dbdb4850293caae4559ce88b65163f1ea5d4e4b3ac49d772ded14"
-createdAt: DateTime @1545679179 {#442
date: 2018-12-24 19:19:39.0 UTC (+00:00)
}
-id: 43
-loginRole: UserLoginRole {#458
+__isInitialized__: false
-description: null
-id: "ROLE_BUYER"
…2
}
#roles: null
#salt: null
#groups: ArrayCollection {#521
-elements: []
}
}
Here is the YAML config
https://pastebin.com/MRBqzKXD
Or any idea how can I debug it?
Also what i found now, I debug Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage:getToken()
dump('dsf', $this->token); exit;
this->token is null, why?