Programatically login to frontend


#1

I have set up a Web-Site using CMS including form login, which works perfect.
The web-site is to be included into an Intranet.
It is therefore required that the login to my site is also via a post request to a specific uri.

How can I programatically login a user, create a session et.al.?

Any hint ist apreciated.

Regards Roman


#2

https://www.google.com/search?q=symfony+login+user+programmatically&oq=symfony+login+user&aqs=chrome.2.69i57j0l5.2779j0j7&sourceid=chrome&ie=UTF-8

I guess you are using Pimcore 5 with Symfony.


#3

Thanks for your advice.

I got the following code working:

$user = Tool\Authentication::authenticatePlaintext($_user,$_password);
// Check if the user exists !
if(!$user){
return new Response(
‘Username or Password not valid.’,
Response::HTTP_UNAUTHORIZED,
array(‘Content-type’ => ‘application/json’)
);
}

    // Handle getting or creating the user entity likely with a posted form
    // The third parameter "main" can change according to the name of your firewall in security.yml
    $token = new UsernamePasswordToken($user->getUsername(), null, $firewallName, $user->getRoles());
    $this->get('security.token_storage')->setToken($token);
	
    // If the firewall name is not main, then the set value would be instead:
    // $this->get('session')->set('_security_XXXFIREWALLNAMEXXX', serialize($token));
    $this->get('session')->set('_security_'.$firewallName, serialize($token));
    
    // Fire the login event manually
    $event = new InteractiveLoginEvent($request, $token);
    $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
    
    /*
     * Now the user is authenticated !!!! 
     * Do what you need to do now, like render a view, redirect to route etc.
     */
</code>

The user is now logged in “the symfony way”.
But i do get errors when subsequent code wants to access the $user object from the session.
I assume that pimcore does not know about the successfull login.
How can I inform pimcore abouet that?