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