Symfony 6.3 client->loginUser does not work

131 Views Asked by At

I have an issue that i don't understant. I m trying to make a fonctionnal test but i need to authenticate my user. I have this following code :

`it('test profileController page profile', function () {

self::ensureKernelShutdown();
$client = static::createClient();

$userRepository = static::getContainer()->get(UserRepository::class);
$urlGenerator = $client->getContainer()->get('router.default');

// retrieve the test user
$testUser = $userRepository->loadUserByIdentifier('[email protected]');

// simulate $testUser being logged in
$client->loginUser($testUser);

$client->request(
    Request::METHOD_GET, 
    $urlGenerator->generate('profile', ['_locale' => 'fr'])
);

$statusCode = $client->getResponse()->getStatusCode();
expect($statusCode)->toBe(200);

})->group('in_work');`

This code work but i m not authenticated so the controller redirect me to the home page and my test send me a failed asertion :

Failed asserting that 302 is identical to 200.

I want to create an authenticated user but i don't now why it does not work. I m using symfony 6.3 and pest for testing.

I had check $testUser, it not null and implement UserInterface. I had try to set roles in my user, try to use differents user, but in my controller, $this->getUser() always return null.

1

There are 1 best solutions below

0
Rehark On

I found the probleme, i use different Authenticator with 'custom_authenticator' in security.yaml,

add this in your firewall in security.yaml

entry_point: App\Security\LoginAuthenticator \n http_basic: ~

And loginUser will use the correct Authenticator ! Hope it will help people in the future