Skip to content

Instantly share code, notes, and snippets.

@azhararmar
Last active June 21, 2024 08:44
Show Gist options
  • Save azhararmar/0a952cf03b1cfbd2a5b059089b764491 to your computer and use it in GitHub Desktop.
Save azhararmar/0a952cf03b1cfbd2a5b059089b764491 to your computer and use it in GitHub Desktop.
Manually Authenticate User In Symfony
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));
@juneodev
Copy link

Thank you so much @azhararmar

@ZaneCEO
Copy link

ZaneCEO commented May 5, 2021

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));

            // ....
    }

@DennisdeBest
Copy link

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');

@yyaremenko
Copy link

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));
    }
}

@Hemric
Copy link

Hemric commented Aug 30, 2021

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