Answer the question
In order to leave comments, you need to log in
How to set a session token in Symfony when authenticating?
Hi
I'm doing ajax login in symfony, I encountered the fact that after registration the user session does not appear, therefore any requests of the type:
$request->getSession(); - return null
$request->getUser() - return null
__
What I did:
security.yaml
firewalls:
main:
anonymous: ~
pattern: ^/
http_basic: ~
provider: our_db_provider
form_login:
login_path: index #редиректит сюда, если нет логина
check_path: login #отрабатывает функцию логина
success_handler: authentication_handler
failure_handler: authentication_handler
logout:
path: logout
target: /
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface,
AuthenticationFailureHandlerInterface
{
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($request->isXmlHttpRequest()) {
$response = new JsonResponse([
'reload' => 'reload',
]);
return $response;
} else {
$redirect = new RedirectResponse("index");
return $redirect;
}
}
Answer the question
In order to leave comments, you need to log in
Symfony 4
Custom can be done like this (if I understand you correctly):
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class SecurityService
{
private $authenticationManager;
private $tokenStorage;
public function __construct(
AuthenticationManagerInterface $authenticationManager,
TokenStorageInterface $tokenStorage,
)
{
$this->authenticationManager = $authenticationManager;
$this->tokenStorage = $tokenStorage;
}
public function test()
{
$user = ...; // entity User
$unauthenticatedToken = new UsernamePasswordToken(
$user,
$user->getPlainPassword(),
'main'
);
$authenticatedToken = $this
->authenticationManager
->authenticate($unauthenticatedToken);
$this->tokenStorage->setToken($authenticatedToken);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question