Customizing Errors & Logout

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

If we enter an email that doesn't exist, we get this

Username could not be found

error message. And, as we saw a moment ago, if we return false from checkCredentials(), the error is something about "Invalid credentials".

The point is, depending on where authentication fails, the user will see one of these two messages.

The question now is, what if we want to customize those? Because, username could not be found? Really? In an app that doesn't use usernames!? That's... confusing.

Customizing Error Messages

There are two ways to control these error messages. The first is by throwing a very special exception class from anywhere in your authenticator. It's called CustomUserMessageAuthenticationException. When you do this, you can create your own message. We'll do this later when we build an API authenticator.

The second way is to translate this message. No, this isn't a tutorial about translations. But, if you look at your login template, when we print this error.messageKey thing, we are already running it through Symfony's translation filter:

... lines 1 - 10
{% block body %}
<form class="form-signin" method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
... lines 16 - 29
</form>
{% endblock %}

Another way to look at this is on the web debug toolbar. See this little translation icon? Click that! Cool: you can see all the information about translations that are being processed on this page. Not surprisingly - since we're not trying to translate anything - there's only one: "Username could not be found."... which... is being translated into... um... "Username could not be found."

Internally, Symfony ships with translation files that will translate these authentication error messages into most other languages. For example, if we were using the es locale, we would see this message in Spanish.

Ok, so, why the heck do we care about all of this? Because, the errors are passed through the translator, we can translate the English into... different English!

Check this out: in your translations/ directory, create a security.en.yaml file:

... lines 1 - 10
{% block body %}
<form class="form-signin" method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
... lines 16 - 29
</form>
{% endblock %}

This file is called security because of this security key in the translator. This is called the translation "domain" - it's kind of a translation category - a way to organize things.

Anyways, inside the file, copy the message id, paste that inside quotes, and assign it to our newer, hipper message:

Oh no! It doesn't look like that email exists!

"Username could not be found.": "Oh no! It doesn't look like that email exists!"

That's it! If you go back to your browser and head over to the login page, in theory, if you try failing login now, this should work instantly. But... no! Same message. Today is not our lucky day.

This is thanks to a small, um, bug in Symfony. Yes, yes, they do happen sometimes, and this bug only affects our development... slightly. Here's the deal: whenever you create a new translation file, Symfony won't see that file until you manually clear the cache. In your terminal, run:

php bin/console cache:clear

When that finishes, go back and try it again: login with a bad email and... awesome!

Logging Out

Hey! Our login authentication system is... done! And... not that I want to rush our moment of victory - we did it! - but now that our friendly alien users can log in... they'll probably need a way to log out. They're just never satisfied...

Right now, I'm still logged in as spacebar1@example.com. Let's close a few files. Then, open SecurityController. Step 1 to creating a logout system is to create the route. Add public function logout():

... lines 1 - 8
class SecurityController extends AbstractController
{
... lines 11 - 30
public function logout()
{
... line 33
}
}

Above this, use the normal @Route("/logout") with the name app_logout:

... lines 1 - 5
use Symfony\Component\Routing\Annotation\Route;
... lines 7 - 8
class SecurityController extends AbstractController
{
... lines 11 - 27
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
... line 33
}
}

And this is where things get interesting... We do need to create this route... but we don't need to write any logic to log out the user. In fact, I'm feeling so sure that I'm going to throw a new Exception():

will be intercepted before getting here

... lines 1 - 8
class SecurityController extends AbstractController
{
... lines 11 - 27
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \Exception('Will be intercepted before getting here');
}
}

Remember how "authenticators" run automatically at the beginning of every request, before the controllers? The logout process works the same way. All we need to do is tell Symfony what URL we want to use for logging out.

In security.yaml, under your firewall, add a new key: logout and, below that, path set to our logout route. So, for us, it's app_logout:

security:
... lines 2 - 8
firewalls:
... lines 10 - 12
main:
... lines 14 - 19
logout:
path: app_logout
... lines 22 - 36

That's it! Now, whenever a user goes to the app_logout route, at the beginning of that request, Symfony will automatically log the user out and then redirect them... all before the controller is ever executed.

So... let's try it! Change the URL to /logout and... yes! The web debug toolbar reports that we are once again floating around the site anonymously.

By the way, there are a few other things that you can customize under the logout section, like where to redirect. You can find those options in the Symfony reference section.

But now, we need to talk about CSRF protection. We'll also add remember me functionality to our login form with almost no effort.

Leave a comment!

  • 2020-04-27 Victor Bocharsky

    Hey Nicky,

    Yes, sure it's possible! Symfony Guard system is very flex for such kind of things. I think checkCredentials() is the perfect place for doing this check. So, you can check that credentials are valid, and then add one more check to make sure that user account is activated. If not - you may want to throw a specific exception with a custom method - CustomUserMessageAuthenticationException is what you need, see https://symfony.com/doc/cur...

    Cheers!

  • 2020-04-25 Nicky Speight

    Hi,
    I don't know if I am following the most recent judging by the age of the comments. But I was wanting to ask. I have a registration process that requires users to authenticate their email. This email is sent fine. It updates a status in the DB to be awaiting activation. Prior to following this tutorial status was checked and login denied even if credentials where correct. This process allows me to block users if accounts are at risk etc.

    Is it possible to incorporate this process into the login authenticator so that if a user exists and they typed the credentials in correctly they can still be rejected based on the status of their account.

    Thank you and thanks for all the work on these tutorials as well.

  • 2019-10-30 Victor Bocharsky

    Hey John,

    Tricky question :) Hm, probably the easiest way is to redirect user to a specific page after he's logged out, e.g. when user logout - redirect him to the "/logged-out". Then, create a controller for this URL, add a flash message there, and do one more redirect :) So it is like this workflow:

    1. User click Logout

    2. System sends him to "/logout" URL that is handled by framework and do actually log out the user, clearing the session.

    3. In your configuration, system sees that it should redirect the logged out user to a specific page, i.e. "/logged-out" in our case

    4. User is redirected to the "/logged-out" page, and user has already a new *cleared* session.

    5. You set a new flash message to the new user session and redirect him one more time to whatever page you want

    6. And finally the user see your flash message

    IMO it's the best way in case you really want the real flash message to be displayed. Otherwise, you can just try to write/read some flags from/to the cookies and display some kind of flash message. Or just simply redirect users to a specific page that has that "You're logged out" message hardcoded in the HTML. To avoid hitting this URL accidentally by users - you can do some extra checks on HTTP referer of the request, and if the request was not came from your website, or from the specific page - just redirect to the homepage and do not show this special page with the message to users.

    I hope this helps!

    Cheers!

  • 2019-10-25 John

    Hi,

    I was wondering what method would you recommend for add a flash message to the user logging out, such as "You logged out!".

    Making a class that implements LogoutSuccessHandlerInterface (success_handler key in security.yaml/logout:), adds the flash and redirect into onLogoutSuccess() method seems to me to be clean but the problem is that each time you disconnect the session is completely empty.

    Result, flash is deleted even before you can display it.

    I found some solutions but old or bad practices. I think there is a better method.

    Thank you for your work !

  • 2019-10-07 Nicolas Caballero Rau

    ok, I fixed it already – thank you! ;-)

  • 2019-10-07 Victor Bocharsky

    Hey Nicolas,

    Hm, check your indentation probably. Anyway, it should be "security.firewalls.main.logout", not just "security.firewalls.logout". So, maybe you missed the level or confuse your indentation. Both good to check

    Cheers!

  • 2019-10-06 Nicolas Caballero Rau

    Hello, when I set in the security.yaml file => logout: path: app_logout and clean the cache in terminal app I get the following error message: "Unrecognized option "path" under "security.firewalls.logout" dou you know how to fix it? Thank you - Nico -

  • 2019-05-28 Victor Bocharsky

    Hey YunierHdz,

    We're sorry about that. What exactly error do you mean? I just was able to watch this video up to the end and it works for me. Please, could you refresh the page and try again? Do you still see this issue?

    Cheers!

  • 2019-05-28 YunierHdz

    the video has an error and it is not finished seeing

  • 2019-01-17 Diego Aguiar

    Hey Emin

    Thanks for sharing it, that's a useful workaround when the "clear cache" command doesn't work properly

    Cheers!

  • 2019-01-15 Emin

    Hey!

    for those who don't see changes after cache:clear try rm -rf var/cache/* in the directory you are working from. Apperently sometimes symfony doesn't delete the cache, so you have to manually remove it in order to make it work :)

    Cheers!

  • 2018-12-17 Victor Bocharsky

    Hey Usuri,

    Yes, it's possible. You just need to register a listener. Actually, you can take a look at Symfony Demo: https://github.com/symfony/... - it has something similar to what you're looking for.

    Cheers!

  • 2018-12-15 Usuri

    Is it possible to change locale language automatically depends of user language detected in cookies?

  • 2018-11-28 Victor Bocharsky

    Hey Alex,

    Haha, yeah, "symfony/translation" is required by "knplabs/knp-time-bundle" that we have installed as a dependency, so if you don't install "knp-time-bundle" - you need to "composer require symfony/translation" manually. Thanks for this tip!

    Cheers!

  • 2018-11-27 Alex Finnarn

    I may have fudged a little bit when setting up the initial dependencies, but I had to require the translation component, "composer require symfony/translation", in order to see the translation tab in the Web Profiler and use the translation service...just FYI in case someone else doesn't see the translation tab when you get to that step.

  • 2018-10-05 Diego Aguiar

    Hey Ahmad Mayahi

    Do you have sessions enabled in your project? if so, it should be done automatically

    Cheers!

  • 2018-10-05 Ahmad Mayahi

    The AUTHENTICATION_ERROR will not be saved in the session, so I have to set it manually in onAuthenticationFailure method:


    $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);


    Any idea why?

  • 2018-09-27 Victor Bocharsky

    Hey Ahmed,

    Oh, wait, but Symfony Form Component does not translate the input unless you do it by yourself, i.e. manually user |trans Twig filter for the input value. It translates only form field labels. Or do you use Google Translator to translate the whole page? Could you show me this field HTML layout?

    Cheers!

  • 2018-09-26 Ahmed Wali

    Hello Victor Bocharsky,
    My problem is when i set locale: 'ar'
    and go to my product edit form i found the value of the input like this ١٢٠ instead of 120 and the value doesn't appear and when submit it's not validated

  • 2018-09-26 Victor Bocharsky

    Hey Ahmed,

    If you do not want to translate field labels, you can set translation_domain to false, see: https://symfony.com/doc/cur...

    Cheers!

  • 2018-09-25 Ahmed Wali

    Hello Ryan,
    How to disable translate in input value

  • 2018-09-24 Stéphane

    Thank for your advice. It's working perfectly now.

  • 2018-09-24 Victor Bocharsky

    Hey Stephane,

    Did you enable translator in your project? If translator is enabled, then @niumis advice below may help, try to change locale value in "config/services.yaml"

    Cheers!

  • 2018-09-23 niumis

    Hello, Stéphane,
    Change in services.yaml 'locale' parameter ;)

  • 2018-09-22 Stéphane

    Hey Ryan,
    I try to change the default_locale in framework.yaml config file for translate message in french but it is not working. I don't understand why. I have php-intl extension installed.