我有一个例子,我试图创建一个使用Symfony2和FOSUserBundle的AJAX登录。我在我的security.yml
文件中设置了我自己的success_handler
和failure_handler
的form_login
。Symfony2 AJAX登录
这里是类:
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的标准登录。
我有同样的确切问题。我在这里发布了一个问题:http://stackoverflow.com/questions/8654265/calling-default-handler-from-a-custom-authentication-handler但现在没有答案:( – 2011-12-28 10:32:07
有一个伟大的文章解释如何做这在这里:http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/ – joe42 2014-03-07 12:51:36