title: AngularJS/AJAX Authentication using Spring Security - return JSON response
body: <p><strong>Spring Security Configuration</strong></p>
  
  <pre><code>&lt;security:form-login login-page="/login"
          default-target-url="/myapp" always-use-default-target="true"
          authentication-success-handler-ref="myAuthenticationSuccessHandler" 
          authentication-failure-handler-ref="myAuthenticationFailureHandler" /&gt;
  
  &lt;bean id="myAuthenticationSuccessHandler"
          class="com.myapp.auth.AjaxAuthenticationSuccessHandler" /&gt;
  
  &lt;bean id="myAuthenticationFailureHandler"
          class="com.myapp.auth.AjaxAuthenticationFailureHandler" /&gt;
  </code></pre>
  
  <p><strong>The Success and Failure Handler Bean classes:</strong></p>
  
  <pre><code>public class AjaxAuthenticationSuccessHandler extends
  SimpleUrlAuthenticationSuccessHandler {
  
  public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication auth)
      throws IOException, ServletException {
  
      response.getWriter().print(
              "{'login': 'SUCCESS'}");
      response.getWriter().flush();
  
  }}
  
  
  public class AjaxAuthenticationFailureHandler extends
  SimpleUrlAuthenticationFailureHandler {
  
  public void onAuthenticationFailure(HttpServletRequest request,
      HttpServletResponse response, Authentication auth)
      throws IOException, ServletException {
      System.out.println("Login Failed...");
      response.getWriter().print(
              "{'login': 'FAIL'}");
      response.getWriter().flush();
  
  }}
  </code></pre>
  
  <p><strong>Question:</strong><br>
  The login form is submitted via AJAX/Angular application as a Form Post, but the response is expected as a JSON (no redirects)</p>
  
  <p>The login success case invokes onAuthenticationSuccess successfully, so i can return JSON.<br>
  But login failure case <strong><em>does not</em></strong> invoke onAuthenticationFailure at all. Instead i see 401 response directly.<br><br>
  What am i doing wrong ? Or Any other ideas to implement this behavior?</p>