Skip to content

Document how to authenticate a user "manually" #15506

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Nyholm opened this issue Jul 12, 2021 · 4 comments
Closed

Document how to authenticate a user "manually" #15506

Nyholm opened this issue Jul 12, 2021 · 4 comments

Comments

@Nyholm
Copy link
Member

Nyholm commented Jul 12, 2021

Scenario: You have just registered a user and you want to make sure they get the proper session cookies before you send them to their personal dashboard.

@Nyholm
Copy link
Member Author

Nyholm commented Aug 14, 2021

So one should use UserAuthenticatorInterface::authenticateUser()

@Nyholm
Copy link
Member Author

Nyholm commented Nov 17, 2021

I've been at this issue many times...
With Symfony's new authentication system introduced in 5.2 you may create a class like this:

namespace App\Security;

use App\Entity\User\User;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;

/**
 * Login a user programmatically.
 */
class UserAuthenticator
{
    private $requestStack;
    private $symfonyAuthenticator;
    private $authenticator;

    public function __construct(UserAuthenticatorInterface $symfonyAuthenticator, AuthenticatorInterface $authenticator, RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
        $this->symfonyAuthenticator = $symfonyAuthenticator;
        $this->authenticator = $authenticator;
    }

    public function loginUser(User $user): ?Response
    {
        $request = $this->requestStack->getMainRequest();

        return $this->symfonyAuthenticator->authenticateUser($user, $this->authenticator, $request, []);
    }
}

The Authenticator is used for the "success handler". Since Im using the FormAuthenticator and my firewall is called default I can use the following service definition:

App\Security\UserAuthenticator:
        autowire: true
        arguments:
            $authenticator: '@security.authenticator.form_login.default'

@javiereguiluz
Copy link
Member

Closing in favor of #17016.

@xabbuh
Copy link
Member

xabbuh commented Aug 24, 2022

actually the duplicating issue is #16940

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants