title: Symfony2 firewall and FOSRestBundle
body: <p>For my web service using FOSRestBundle, I created a firewall that forces a login to access the application. </p>
  
  <p>My problem is that when I make a call to the API via ajax, I need to get the error code 401 when the user is not authenticated rather than receive the html source code of the login form. How do I configure the application?</p>
  
  <pre><code>secured_area:
              pattern:    ^/
              form_login:
                  provider: fos_userbundle
                  use_forward: false
                  default_target_path: /w
              logout:
                  path:   /logout
                  target: /login
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Thanks to Ryan here is the KernelExceptionListener method.</p>
  
  <pre><code>public function onKernelException( GetResponseForExceptionEvent $event ) {
      // get exception
      $exception = $event-&gt;getException();
      // get path
      $path = $event-&gt;getRequest()-&gt;getPathInfo();
  
      if ( $exception instanceOf AuthenticationException &amp;&amp; ($event-&gt;getRequest()-&gt;isXmlHttpRequest() || strpos( $path, '/api' ) === 0) ) {
          $response = new Response();
          $response-&gt;setStatusCode( 401 );
          $event-&gt;setResponse( $response );
          $event-&gt;stopPropagation();
      }
  }
  </code></pre>