我有一個例子,我試圖創建一個使用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