Install flashMessage from AuthenticationHandler in Symfony2

I have a problem with FOSUserBundle since I login with bad credentials. I am getting the full stack as an error message:

Mistake! 'Symfony \ Component \ Security \ Core \ Exception \ BadCredentialsException' with "Bad Credentials" message in / var / www / html / vendor / symfony / symfony / src / Symfony / Component / Security / Core / Authentication / Provider / UserAuthenticationProvider .php: 90

And this is ugly to me, so very ugly for users. So I am thinking of two solutions: go to the AJAX login that I am working on but it doesnโ€™t work, or I am doing something wrong (explain below) and found a way to change this ugly message (I didnโ€™t get this yet another one, so any advice will be helpful).

Now about the first solution, this is what I did:

  • Implements AuthenticationHandler

    :

    <?php
    
    namespace UsuarioBundle\Handler;
    
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Bundle\FrameworkBundle\Routing\Router;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
    use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
    use Symfony\Component\Security\Core\Exception\AuthenticationException;
    
    class AuthenticationHandler
        implements AuthenticationSuccessHandlerInterface,
        AuthenticationFailureHandlerInterface
    {
        private $router;
    
        public function __construct(Router $router)
        {
            $this->router = $router;
        }
    
        public function onAuthenticationSuccess(Request $request, TokenInterface $token)
        {
            if ($request->isXmlHttpRequest()) {
                // do I need something here?
            } else {
                // If the user tried to access a protected resource and was forces to login
                // redirect him back to that resource
                if ($targetPath = $request->getSession()->get('_security.target_path')) {
                    $url = $targetPath;
                } else {
                    // Otherwise, redirect him to wherever you want
                    $url = $this->router->generate('user_view', array('nickname' => $token->getUser()->getNickname()));
                }
    
                return new RedirectResponse($url);
            }
        }
    
        public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
        {
            if ($request->isXmlHttpRequest()) {
                // Handle XHR here
            } else {
                // Create a flash message with the authentication error message
                $request->getSession()->setFlash('error', $exception->getMessage());
                $url = $this->router->generate('user_login');
    
                return new RedirectResponse($url);
            }
        }
    }
    
          

  • Define a service and register a handler:

    parameters:
        vendor_security.authentication_handler: UsuarioBundle\Handler\AuthenticationHandler
    
    services:
        authentication_handler:
            class:  %vendor_security.authentication_handler%
            arguments:  [@router]
            tags:
                - { name: 'monolog.logger', channel: 'security' }
    
          

  • Change the links to security.yml

    :

    firewalls: master: sample: ^ / form_login: provider: fos_userbundle csrf_provider: form.csrf_provider login_path: / login check_path: / login_check success_handler: authentication_handler fail_handler: authentication_handler

          logout:
               path: fos_user_security_logout
               target: /
               invalidate_session: false
          anonymous: ~
    
          

But I am getting this error when I try to login with invalid credentials:

Attempting to call the setFlash method in the "Symfony \ Component \ HttpFoundation \ Session \ Session" class in /var/www/html/src/UsuarioBundle/Handler/AuthenticationHandler.php line 52.

Why? I am testing the method getSession()

and the part HttpFoundation

that I include in the instructions use

, so what am I doing wrong here?

Note. I am taking the code mostly from this , so I still have some doubts for this.

+3


source to share


1 answer


$request->getSession()->setFlash('error', 'error');

was the designation for the "old" version of symfony.

You should now use



$reqest->getSession()->getFlashBag()->add('error', $exception->getMessage());

      

Also, are you sure it's good practice to show a text message $exception

? I mean, I don't know which page this flash will be displayed on, but if a user or even an administrator who of course knows little about PHP and programming in general can see this page, and so the message, you should try to register the message for their purpose, but show something else to the user.

+9


source







All Articles