Skip to content

Instantly share code, notes, and snippets.

@azhararmar
Last active June 16, 2023 15:35
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));
@magarrent
Copy link

Wow, very thanks @azhararmar I've viewed a lot of unusefull tutorials, that's all I need!

@warthy
Copy link

warthy commented May 28, 2018

I have seen in this example (Symfony 3), that they fire the login event . https://ourcodeworld.com/articles/read/459/how-to-authenticate-login-manually-an-user-in-a-controller-with-or-without-fosuserbundle-on-symfony-3
But I couldn't find the class in my project. If anybody have any hint :)

@stenno
Copy link

stenno commented Jun 13, 2018

Worked like a charm in SF4, thanks!
A small note:
Your User entity needs to implement UserInterface and Serializable as mentioned here: https://symfony.com/doc/current/security/entity_provider.html
Note that no FOSUserBundle or similar is required.

@paoloBirdOffice
Copy link

paoloBirdOffice commented Aug 21, 2018

Hello everyone,
On Symfony 3.4 I do the method in my controller ans then I redirect to a dashboard but after the redirection the session is empty and the user is not logged anymore.
Before the redirection the use is log in.

Any idea what it could be??

public function ConnectAction(Request $request, string $oauth)
    {
        $body = $request->query->all();
        $user = $this->container->get('oauth_manager')->logInUserWithOAuth($oauth, $body);

       if (!$user || $user === null) {
            return $this->redirectToRoute('homepage');
        }

      /** Handle getting or creating the user entity likely with a posted form */
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $this->get('security.token_storage')->setToken($token);
        $session = $request->getSession();
        $session = $this->get('session');
        $session->set('_security_main', serialize($token));

        /** Fire the login event manually */
        $event = new InteractiveLoginEvent($request, $token);
        $eventDispatcher = $this->get('event_dispatcher');
        $eventDispatcher->dispatch('security.interactive_login', $event);

        $url = 'dashboard';
        $response = new RedirectResponse($this->generateUrl($url));
        return $response;

    }

@priatelko
Copy link

priatelko commented Dec 30, 2018

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 login

Dump 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?

@Yozhef
Copy link

Yozhef commented Mar 2, 2020

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

@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