首页 文章

从自定义身份验证处理程序调用默认处理程序[重复]

提问于
浏览
5

可能重复:Symfony2 AJAX登录

我已经实现了一个自定义身份验证处理程序服务来处理AJAX登录请求,如下所示:https://stackoverflow.com/a/8312188/267705

how can I handle normal login requests? 调用默认行为会很好,但我没有找到如何做到这一点 .

1 回答

  • 6

    这是实现您想要的方法之一:

    namespace YourVendor\UserBundle\Handler;
    
    // "use" statements here
    
    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()) {
                // Handle XHR 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);
            }
        }
    }
    

    请享用 . ;)

相关问题