title: FOSUserBundle AJAX Login with Symfony2 (routing)
body: <p>I'm trying to make the AJAX authentication work with FOSUserBundle.</p>
  
  <p>I have created an Handler directory with a <code>AuthenticationHandler class</code> :</p>
  
  <pre><code>&lt;?php
  
  namespace BirdOffice\UserBundle\Handler;
  
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\HttpFoundation\RedirectResponse;
  use Symfony\Component\Routing\RouterInterface;
  use Symfony\Component\HttpFoundation\Session\Session;
  use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  use Symfony\Component\Security\Core\Exception\AuthenticationException;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\Security\Core\SecurityContextInterface;
  use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  
  class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
  {
      private $router;
      private $session;
  
      /**
       * Constructor
       *
       * @param   RouterInterface $router
       * @param   Session $session
       */
      public function __construct( RouterInterface $router, Session $session )
      {
          $this-&gt;router  = $router;
          $this-&gt;session = $session;
      }
  
      /**
       * onAuthenticationSuccess
       *
       * @param   Request $request
       * @param   TokenInterface $token
       * @return  Response
       */
      public function onAuthenticationSuccess( Request $request, TokenInterface $token )
      {
          // if AJAX login
          if ( $request-&gt;isXmlHttpRequest() ) {
  
              $array = array( 'success' =&gt; true ); // data to return via JSON
              $response = new Response( json_encode( $array ) );
              $response-&gt;headers-&gt;set( 'Content-Type', 'application/json' );
  
              return $response;
  
              // if form login
          } else {
  
              if ( $this-&gt;session-&gt;get('_security.main.target_path' ) ) {
  
                  $url = $this-&gt;session-&gt;get( '_security.main.target_path' );
  
              } else {
  
                  $url = $this-&gt;router-&gt;generate( 'home_page' );
  
              } // end if
  
              return new RedirectResponse( $url );
  
          }
      }
  
      /**
       * onAuthenticationFailure
       *
       * @param   Request $request
       * @param   AuthenticationException $exception
       * @return  Response
       */
      public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
      {
          // if AJAX login
          if ( $request-&gt;isXmlHttpRequest() ) {
  
              $array = array( 'success' =&gt; false, 'message' =&gt; $exception-&gt;getMessage() ); // data to return via JSON
              $response = new Response( json_encode( $array ) );
              $response-&gt;headers-&gt;set( 'Content-Type', 'application/json' );
  
              return $response;
  
              // if form login
          } else {
  
              // set authentication exception to session
              $request-&gt;getSession()-&gt;set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);
  
              return new RedirectResponse( $this-&gt;router-&gt;generate( 'login_route' ) );
          }
      }
  }
  </code></pre>
  
  <p>I have created a <code>login Javascript function</code> :</p>
  
  <pre><code>function login() {
      $.ajax({
          type: "POST",
          url: Routing.generate('check_login_ajax'),
          dataType: 'json',
          data: {
              _username: $('#username').val(),
              _password: $('#password').val(),
              _remember_me: false,
              _csrf_token: $('#_csrf_token').val()
          }
      }).done(function(data) {
          console.log(data);
      }).fail(function(data) {
          console.log(data);
      });
  }
  </code></pre>
  
  <p>In my <code>routingAjax.yml</code>, I have added the following lines to override the <code>FOSUserBundle security route</code> :</p>
  
  <pre><code>check_login_ajax:
      pattern:  /check_login_ajax
      defaults: { _controller: FOSUserBundle:Security:check }
      requirements:
          _method:  POST
      options:
          expose: true
  </code></pre>
  
  <p>In my global <code>security.yml</code> file, I have added the <code>check_path</code>, <code>success_handler</code> and <code>failure_handler</code> parts :</p>
  
  <pre><code>firewalls:
          main:
              pattern: ^/
              form_login:
                  login_path: fos_user_registration_register
                  check_path:      check_login_ajax
                  success_handler: user.security.authentication_handler
                  failure_handler: user.security.authentication_handler
                  provider: fos_userbundle
                  csrf_provider: form.csrf_provider
              logout:
                    path:   fos_user_security_logout
                    target: /
              anonymous:    true
  </code></pre>
  
  <p>My first issue is : the AJAX return this message: "Invalid CSRF token." (but I send a good one generated in PHP, maybe I missed something doing it). Here is my PHP code for it :</p>
  
  <pre><code>&lt;?php
    $csrfProvider = $this-&gt;container-&gt;get('form.csrf_provider');
    $csrfToken = $csrfProvider-&gt;generateCsrfToken('popUpUser');
  ?&gt;
  </code></pre>
  
  <p>Second issue : my login page (not the AJAX one) is not working anymore because the orignal route of FOSUserBundle login has been overwritten.</p>
  
  <p>PS : I have posted a message yesterday : <a href="https://stackoverflow.com/questions/28611087/fosuserbundle-login-register-ajax-symfony2">FOSUserBundle (login / register) + AJAX + Symfony2</a> but I have badly explained my problem. Sorry by advance.</p>