【问题标题】:Calling default handler from a custom authentication handler [duplicate]从自定义身份验证处理程序调用默认处理程序 [重复]
【发布时间】:2011-12-28 09:49:42
【问题描述】:

可能重复:
Symfony2 AJAX Login

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

但是我怎样才能处理正常的登录请求?调用默认行为会很好,但我不知道也没有找到怎么做。

【问题讨论】:

  • 你所说的handle到底是什么意思?
  • 看问题中的链接,我的意思是 void else 语句。
  • 好吧,我写了你链接到的答案。 ;) 我不明白你所说的 handle 是什么意思。如果没有技术细节,您的用例是什么?
  • 哦好的 :) 我想处理 Ajax 登录和正常登录。所以我实现了你的身份验证处理程序。 Ajax 工作正常,但正常登录不能,因为它属于 else,所以我必须返回一些东西。我想返回显示错误的登录页面,或在成功登录后重定向,作为默认行为。但是对于您的身份验证处理程序,我不知道该怎么做。

标签: symfony


【解决方案1】:

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

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

享受。 ;)

【讨论】:

  • 在身份验证失败时生成“user_login”路由时出现错误。无论我尝试什么(登录、登录路径、用户登录),都无法生成路由,并且出现“路由不存在”错误。这条路线在哪里配置?我该如何修改它才能生成它?
  • @GabrielTheron,这只是您为常规操作定义的常规路线。阅读section on traditinal login forms
  • 感谢您的回答,我正在使用 FOSUserBundle,我认为它会覆盖这条路线以使用“fos_user_security_login”。这是唯一对我有用的路径。
猜你喜欢
  • 1970-01-01
  • 2010-11-08
  • 2017-10-19
  • 1970-01-01
  • 2017-06-22
  • 2012-04-13
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多