Friday, July 13, 2012

php - How to disable redirection after login_check in Symfony 2 - Stack Overflow

php - How to disable redirection after login_check in Symfony 2 - Stack Overflow


Create an authentication handler:
namespace YourVendor\UserBundle\Handler;
// "use" statements here
class AuthenticationHandler
implements AuthenticationSuccessHandlerInterface,
           AuthenticationFailureHandlerInterface
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => true);
            return new Response(json_encode($result));
        } else {
            // Handle non XmlHttp request here
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => false);
            return new Response(json_encode($result));
        } else {
            // Handle non XmlHttp request here
        }
    }
}
Register the handler as a service:
services:
    authentication_handler:
        class: YourVendor\UserBundle\Handler\AuthenticationHandler
Register the service in the firewall:
firewalls:
    main:
        form_login:
            success_handler: authentication_handler
            failure_handler: authentication_handler
This is a rough example to give you the general idea — you'll need to figure out the details by yourself. 


PS:
this will solve all problem after login , especially after login redirection

PS:
how to do redirection and add error message


    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => false);
            return new Response(json_encode($result));
        } else {
            // Handle non XmlHttp request here
            $path = $request->request->get('_onFailure_target');
           
            $session = $request->getSession();
                     
            $session->set(SecurityContext::AUTHENTICATION_ERROR, 'email or password incorrect');
                               
            return new RedirectResponse($path);
           
        }
    }


More than 3 requests, I'll translate this to Chinese.
超过3个请求,我就会把这篇文章翻译成中文。

No comments: