2014-09-27 58 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