2013-03-26 226 views
1

我正在使用spring security登錄+ ajax登錄。如果用戶提供了錯誤的憑據,我需要顯示一條消息,指出「無效的用戶/密碼」使用spring security和ajax登錄處理無效用戶/密碼

這是ajax登錄jQuery代碼。

$(document).ready(function(){ 
$('#login_btn').click(function(){ 
    //alert("aaa"+validateLoginForm()); 
    if(validateLoginForm()){ 

     sprpst = 'j_username='+$('#j_username').val()+'&j_password='+$('#j_password').val(); 
     $.post('j_spring_security_check',sprpst,function(data1) { 

      window.location.reload(); 

     }); 
     $.blockUI({ message : '<h1><img src="images/busy.gif" /> Loading...</h1>' }); 
    } 
}); 
}); 

這是春天的安全登錄

<form-login login-page="/login" default-target-url="/deals" authentication-failure-url="/deals?login_error=1"/> 

任何幫助將不勝感激。

謝謝:)

回答

2

您需要:

  1. 提供一個自定義的AuthenticationEntryPoint(也可以使用默認LoginUrlAuthenticationEntryPoint作爲基類)。在AuthenticationEntryPoint.commence(...)方法檢查這是AJAX調用並返回403代碼,而不是重定向到登錄頁面。
  2. 在Spring Security conf中設置您的自定義AuthenticationEntryPoint。
  3. 檢查AJAX響應的代碼。如果它包含403,則顯示有關錯誤憑證的相應錯誤消息。

定製的身份驗證入口點的代碼可能看起來像:

public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { 

    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { 
     String header = request.getHeader("X-Requested-With"); 
     if (StringUtils.hasText(header) && header.equals("XMLHttpRequest") && authException != null) { 
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED); 
     } else { 
      super.commence(request, response, authException); 
     } 
    } 
} 
+0

可以ü請自定義提供的鏈接/示例代碼的AuthenticationEntryPoint – prakash 2013-03-26 10:04:47

+0

我不知道我的回答是更新 – 2013-03-26 10:29:26

+0

,可能是你需要將此代碼放置在自定義的AuthenticationFailureHandler中。 – 2013-03-26 12:36:01