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