2012-10-04 101 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"%> 

下面的标签库...