Symfony2 AJAX Login
我有一个例子,我试图使用Symfony2和FOSUserBundle创建AJAX登录名。我正在我的文件中设置自己的和下面的。success_handlerfailure_handlerform_loginsecurity.yml
这是类:
class AjaxAuthenticationListener implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
/**
* This is called when an interactive authentication attempt succeeds. This
* is called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @see \Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener
* @param Request $request
* @param TokenInterface $token
* @return Response the response to return
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
/**
* This is called when an interactive authentication attempt fails. This is
* called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @param Request $request
* @param AuthenticationException $exception
* @return Response the response to return
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($request->isXmlHttpRequest()) {
$result = array('success' => false, 'message' => $exception->getMessage());
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
}
这对于处理成功和失败的 AJAX 登录尝试非常有用。但是,启用后 - 我无法通过标准表单POST方法(非AJAX)登录。我收到以下错误:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse() must be an instance of Symfony\Component\HttpFoundation\Response, null given
我希望我的和重写仅针对 XmlHttpRequests(AJAX 请求)执行,如果不是,则简单地将执行交还给原始处理程序。onAuthenticationSuccessonAuthenticationFailure
有没有办法做到这一点?
TL;DR 我希望AJAX请求的登录尝试返回JSON响应以确认成功和失败,但我希望它不会影响通过表单POST进行的标准登录。