2014-09-27 55 views
1

春季安全配置AngularJS/AJAX验证使用Spring安全 - 返回JSON响应

<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" /> 

<bean id="myAuthenticationSuccessHandler" 
     class="com.myapp.auth.AjaxAuthenticationSuccessHandler" /> 

<bean id="myAuthenticationFailureHandler" 
     class="com.myapp.auth.AjaxAuthenticationFailureHandler" /> 

成功和失败处理器bean类:

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(); 

}} 

问:
的登录表单通过AJAX/Angular应用程序作为Form Post发送,但是响应e预计为JSON(无重定向)

登录成功案例成功调用onAuthenticationSuccess,因此我可以返回JSON。
但登录失败案例并不是根本就调用onAuthenticationFailure。相反,我直接看到401响应。

我在做什么错?或者其他任何想法来实现这种行为?

回答

3

在AjaxAuthenticationFailureHandler为onAuthenticationFailure正确的方法签名(注意:此方法的最后一个参数):

public void onAuthenticationFailure(javax.servlet.http.HttpServletRequest request, 
     javax.servlet.http.HttpServletResponse response, AuthenticationException exception) 
{ 

    try { 
     response.getWriter().print(
       "{'login': 'FAILURE'}"); 
     response.getWriter().flush(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

能解决问题。

+0

它是否帮助您在使用'SimpleUrlAuthenticationSuccessHandler'时管理会话或登录会话?因为我想用的是'SavedRequestAwareAuthenticationSuccessHandler'。我不清楚他们之间的区别。你能帮我吗 ? – agpt 2015-04-15 05:26:36

+0

agpt>我不知道SavedRequestAwareAuthenticationSuccessHandler ..对不起。也许检查javadocs ... – Jasper 2015-04-15 06:58:29

+0

好吧..没问题,但你能简单介绍一下你在javascript端维护session/cookies的方式吗?你有没有遇到过任何问题?谢谢 – agpt 2015-04-15 07:00:54