Mam przykład, w którym próbuję utworzyć login AJAX za pomocą Symfony2 i FOSUserBundle. Ustawię własne success_handler
i failure_handler
pod form_login
w moim pliku .Symfony2 AJAX Login
Oto klasa:
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;
}
}
}
Działa to doskonale nadaje się do obsługi zarówno sukces i udało AJAX prób logowania. Jednak po włączeniu - nie mogę się zalogować przy użyciu standardowej metody POST (nie AJAX). I pojawia się następujący błąd:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse() must be an instance of Symfony\Component\HttpFoundation\Response, null given
chciałbym dla moich onAuthenticationSuccess
i onAuthenticationFailure
zadajnikami być wykonywane tylko przez XMLHttpRequests (żądań AJAX) i po prostu oddać wykonanie z powrotem do oryginalnego przewodnika czy nie.
Czy istnieje sposób, aby to zrobić?
TL; DR Chcę, aby AJAX żądał prób logowania, aby zwrócić odpowiedź JSON na sukces i porażkę, ale chcę, aby nie wpłynęła na standardowe logowanie poprzez formularz POST.
Mam dokładnie taki sam problem. I napisali pytanie tutaj: http://stackoverflow.com/questions/8654265/calling-default-handler-from-a-custom-authentication-handler ale nie ma odpowiedzi na teraz :( –
Jest to świetny artykuł wyjaśniający jak to zrobić to tutaj: http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/ – joe42