Launch Authenticator process from controller in Symfony 5+

Viewed 41

I'm trying to write a SSO authentication bundle for Symfony 5.4+

When I try to access pages with security attribute set to true in security.yaml, no problem, my authenticator class automatically launches and runs well. I can authenticated myself and then get a filled user instance in Symfony.

But now, what I'd like to do is a simple login page that would play the authentication process and then redirect the user to a page defined by the application admin in config files (for eventually add an authenticate button in app with public access).

My question is: how can I launch this authentication process from a controller as my login route has a public access (and then authentication system is never launched) ?

Something like that :

class AuthenticationController extends AbstractController
{
    public function login(Request $request, Security $security)
    {
        if (!$this->getUser())
            $security->pleaseLaunchTheAuthenticationProcess()
        
        return new RedirectResponse('/my_path');
    }
}
1 Answers

You can achieve that using the UserAuthenticatorInterface:


    /**
     * @Route("/some-route", name="some_route")
     *
     * @param Request $request
     * @param UserAuthenticatorInterface $userAuthenticator
     * @param AuthenticatorInterface $authenticator
     * @return Response
     */
    public function book(
        Request                     $request,
        UserAuthenticatorInterface  $userAuthenticator,
        AuthenticatorInterface      $authenticator
    ): Response
    {
        if ($this->getUser() instanceof User) {
            $userAuthenticator->authenticateUser($this->getUser(), $authenticator, $request);
        }
        return $this->redirectToRoute('/my_path');
    }

You will have an error about AuthenticatorInterface which cannot be launched. You have to declare it manually in your service.yaml:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        bind:
            $authenticator: '@security.authenticator.form_login.main'
Related