我有一个示例,我尝试使用 Symfony2 和 FOSUserBundle 创建 AJAX 登录。我在我的文件中设置我自己的success_handler和failure_handler下的。form_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
我希望我的onAuthenticationSuccess和onAuthenticationFailure覆盖仅针对 XmlHttpRequests(AJAX 请求)执行,如果没有,则简单地将执行交还给原始处理程序。
有没有办法做到这一点?
TL;DR 我希望 AJAX 请求的登录尝试返回成功和失败的 JSON 响应,但我希望它不会影响通过表单 POST 的标准登录。