Skip to content
Advertisement

Customize new authentication errors messages on Symfony5.3

on my new symfony 5.3 project i just implemented the new authentication system, and it works fine, but my problem is that i can’t customize the authentication errors:

in the method: onAuthentificationFailure in the AbstractLoginFormAuthenticator but in my view it only displays the session error which is normal since my controller calls the getLastAuthenticationError() method.

but how could I display my custom error from my CustomUserMessageAuthenticationException in my view ?

My AbstractLoginFormAuthenticator

JavaScript

My SécurityController:

JavaScript

my view twig(loginform):

JavaScript

Advertisement

Answer

You should extend and override the AbstractLoginFormAuthenticator as opposed to modifying it directly.

Why your approach is not working

In short, you need to throw the Exception before reaching onAuthenticationFailure(), as the AuthenticationException is why onAuthenticationFailure() is called by Symfony.

The onAuthenticationFailure() method is what handles the thrown AuthenticationException from the AuthenticatorManager::executeAuthenticator() process.

JavaScript

The default functionality of AbstractLoginFormAuthenticator::onAuthenticationFailure() uses $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception); which is what is adding the message from the Exception, that is retrieved by calling AuthenticationUtils::getLastAuthenticationError(); which calls $session->get(Security::AUTHENTICATION_ERROR);

JavaScript

How to display a Custom Error Message

There are various points in the application that are called where you can throw the Exception that gets passed to onAuthenticationFailure().

By default Symfony uses the security configuration settings to produce generic messages, but can be overridden by implementing them in your classes.

As the exception is overridden by the conditional mentioned above.

JavaScript

You will need to disable hide_user_not_found, otherwise the CustomUserMessageAuthenticationException will be replaced with a BadCredentialsException('Bad credentials.') exception.

Otherwise skip disabling hide_user_not_found and throw the CustomUserMessageAccountStatusException instead of the CustomUserMessageAuthenticationException.

JavaScript

In the Authenticator class

For an up-to-date usage reference, please read the default FormLoginAuthenticator. Since the tutorials on the Symfony Casts site have not been updated for Symfony 5.

JavaScript

In the UserProvider class

JavaScript

In the UserChecker class

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement