从自定义身份验证处理程序调用默认处理程序 [英] Calling default handler from a custom authentication handler

查看:26
本文介绍了从自定义身份验证处理程序调用默认处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Symfony2 AJAX 登录

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

I have implemented a custom authentication handler service to handle AJAX login requests, as suggested here: https://stackoverflow.com/a/8312188/267705

但是我如何处理正常的登录请求?调用默认行为会很好,但我不知道也没有找到如何去做.

But how can I handle normal login requests? It would be nice to call the default behavior, but I don't know and haven't found how to do it.

推荐答案

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

This is one of the ways to achieve what you want:

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);
        }
    }
}

享受.;)

这篇关于从自定义身份验证处理程序调用默认处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆