简体   繁体   中英

Symfony2: Override exception messages in form login

I've built a login form rendered by this controller action:

public function loginAction() {
    $helper = $this->get('security.authentication_utils');
    return $this->render('SecurityLoginBundle:Login:login.html.twig', array(
                'last_username' => $helper->getLastUsername(),
                'error' => $helper->getLastAuthenticationError(),
    ));
}

If the user does not provide a valid email/password "getLastAuthenticationError()" throws a "BadCredentialsException"; if the user is disabled a "DisabledException" is thrown. Both exception objects have a "message" property but I'd like to change the labels. How do I do that?

An ugly workaround would be to read those messages in my Twig template and replace them with my wording but is there a better way? Like checking the class of the " error " parameter in Twig. Unfortunately

get_class($helper->getLastAuthenticationError())

didn't work - it returns " Security\\LoginBundle\\Controller\\LoginController ".

Thanks!

I had the same problem. I solved it when i see

class Symfony\Component\Security\Http\AuthenticationAuthenticationUtils 

getLastAuthenticationError has default parameter $clearSession =true

So you can handle error and after clear session

    $helper = $this->get('security.authentication_utils');
    $error = $helper->getLastAuthenticationError();

You can also if error is an instance of some Exception throw an Exception with your custom message

    if ($error instanceof BadCredentialsException) {
         throw \Exception('Your Custom exception'); 
    }

Add try catch if you want and create new var $error with your custom message. and after return content message because it's an exception :

    return $this->render('SecurityLoginBundle:Login:login.html.twig', array(
            'last_username' => $helper->getLastUsername(),
            'error' => $error ? $error->getMessage() : null,
    )); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM