2012-10-04 102 views
10

我有一個使用Spring Security 3.0.x的應用程序。在那裏,我有一個自定義AuthenticationProviderSpring安全性驗證異常處理

public class AppAuthenticationProvider implements AuthenticationProvider { 
    @Override 
    public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
     ... 
     if (!check1()) throw new UsernameNotFoundException(); 
     if (!check2()) throw new DisabledException(); 
     ... 
    } 

我想每個異常的發送對自定義響應代碼,例如404 UsernameNotFoundException,403 DisabledException等。現在我只是有認證失敗的URL在我spring安全配置,因此我在authenticate()中的每個異常上重定向到它。

回答

19

驗證失敗處理程序:

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 

@Override 
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 
    super.onAuthenticationFailure(request, response, exception); 
    if(exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) { 
    showMessage("BAD_CREDENTIAL"); 
    } else if (exception.getClass().isAssignableFrom(DisabledException.class)) { 
    showMessage("USER_DISABLED"); 
    } 
} 

配置:

<bean id="customAuthenticationFailureHandler" 
     class="com.apackage.CustomAuthenticationFailureHandler"> 
    <property name="defaultFailureUrl" value="/index.jsp"/> 
</bean> 
<security:http auto-config="true"> 
    <security:form-login default-target-url="/welcome.jsp" authentication-failure-handler-ref="customAuthenticationFailureHandler" /> 
</security:http> 
+0

我在SimpleUrlAuthenticationFailureHandler類中找不到showMessage()方法(我正在使用Spring Security版本3.1.x)。你知道你使用的是哪個版本嗎? –

+0

對不起,showMessage方法特定於我的實現,並非來自spring。原始代碼太多了,無法顯示。 – baraber

+0

@baraber如何將異常類型傳遞給控制器​​方法? – gstackoverflow

14

提供有關身份驗證失敗的原因通常是一個壞主意,因爲它可以爲攻擊者提供有用的信息。例如,它可以允許他們探測有效的帳戶名稱。

如果您需要自定義事情,那麼可以使用authentication-failure-handler-ref注入一個自定義的AuthenticationFailureHandler bean,您可以在其中實現不同的行爲,具體取決於異常。

+0

如何從AuthenticationFailureHandler信息傳遞給控制器​​的方法? – gstackoverflow

5

使用下面的標籤在JSP頁面的定製身份驗證。

<c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'Bad credentials'}"> 
Username/Password entered is incorrect. 
</c:if> 
<c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'User is disabled'}"> 
Your account is disabled, please contact administrator. 
</c:if> 
<c:if test="${fn:containsIgnoreCase(sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message,'A communications error has been detected')}"> 
Database connection is down, try after sometime. 
</c:if> 

還包括用於正常工作

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec"%> 

下面的標籤庫...