Ho un esempio in cui sto cercando di creare un accesso AJAX utilizzando Symfony2 e FOSUserBundle. Sto impostando il mio success_handler
e failure_handler
sotto form_login
nel mio file security.yml
.Symfony2 Login AJAX
Qui è la classe:
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;
}
}
}
Questa grande opera per la gestione sia di successo e non è riuscito AJAX tentativi di accesso. Tuttavia, se abilitato, non riesco ad accedere tramite il metodo POST del modulo standard (non AJAX). Ricevo il seguente errore:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse() must be an instance of Symfony\Component\HttpFoundation\Response, null given
vorrei per i miei onAuthenticationSuccess
e onAuthenticationFailure
sostituzioni per essere eseguita solo per XMLHttpRequests (richieste AJAX) ed a portata di mano semplicemente l'esecuzione torna al gestore originale in caso contrario.
C'è un modo per farlo?
TL; DR Desidero che AJAX richieda i tentativi di accesso per restituire una risposta JSON per il successo e l'insuccesso ma voglio che non influenzi l'accesso standard tramite il modulo POST.
Ho lo stesso problema esatto. Ho postato una domanda qui: http://stackoverflow.com/questions/8654265/calling-default-handler-from-a-custom-authentication-handler ma nessuna risposta per ora :( –
C'è un grande articolo che spiega come fare questo qui: http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/ – joe42