Authentication Spring安全性验证异常处理

Authentication Spring安全性验证异常处理,authentication,exception-handling,spring-security,Authentication,Exception Handling,Spring Security,我有一个使用SpringSecurity3.0.x的应用程序。我有一个自定义的身份验证提供程序: 公共类AppAuthenticationProvider实现AuthenticationProvider{ @凌驾 公共身份验证(身份验证)引发AuthenticationException{ ... 如果(!check1())抛出新用户名NotFoundException(); 如果(!check2())抛出新的DisabledException(); ... } 我想在每个异常上发送cutom

我有一个使用SpringSecurity3.0.x的应用程序。我有一个自定义的
身份验证提供程序

公共类AppAuthenticationProvider实现AuthenticationProvider{
@凌驾
公共身份验证(身份验证)引发AuthenticationException{
...
如果(!check1())抛出新用户名NotFoundException();
如果(!check2())抛出新的DisabledException();
...
}

我想在每个异常上发送cutom响应代码,例如,404代表UsernameNotFoundException,403代表DisableDexException等。现在,我的spring安全配置中只有身份验证失败url,所以我在authenticate()中的每个异常上重定向到它.

提供身份验证失败原因的详细信息通常不是一个好主意,因为它可以为攻击者提供有用的信息。例如,它可以让他们探测有效的帐户名


如果您需要自定义内容,那么您可以使用
身份验证失败处理程序ref
注入自定义bean,在其中您可以根据异常实现不同的行为,而不是使用
身份验证失败url

身份验证失败处理程序:

公共类CustomAuthenticationFailureHandler扩展了SimpleRuthenticationFailureHandler{
@凌驾
AuthenticationFailure(HttpServletRequest请求、HttpServletResponse响应、AuthenticationException异常)上的公共无效引发IOException、ServletException{
super.onAuthenticationFailure(请求、响应、异常);
if(exception.getClass().isAssignableFrom(UsernameNotFoundException.class)){
showMessage(“坏凭证”);
}else if(exception.getClass().isAssignableFrom(DisabledException.class)){
showMessage(“用户禁用”);
}
}
配置:


在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"%>


我在SimpleRuThenticationFailureHandler类中没有找到showMessage()方法(我使用的是Spring安全版本3.1.x)。您知道您使用的是哪个版本吗?抱歉,showMessage方法特定于我的实现,而不是来自spring。原始代码太多,无法显示。@baraber如何将异常类型传递给controller方法?@gstackoverflow-the-controller方法?我的示例中没有控制器,很抱歉,我不理解问题:(如何将信息从AuthenticationFailureHandler传递到控制器方法?