我有一个使用Spring Security 3.0.x的应用程序。我有一个自定义AuthenticationProvider
:
public class AppAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
...
if (!check1()) throw new UsernameNotFoundException();
if (!check2()) throw new DisabledException();
...
}
我想在每个异常上发送cutom响应代码,例如404为UsernameNotFoundException,403为DisabledException等。现在我只在我的spring安全配置中有authentication-failure-url所以我重定向到它在authenticate()中的每个异常。
答案 0 :(得分:22)
身份验证失败处理程序:
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>
答案 1 :(得分:15)
提供身份验证失败原因的详细信息通常是一个坏主意,因为它可以为攻击者提供有用的信息。例如,它可以允许他们探测有效的帐户名称。
如果您需要自定义内容,而不是使用authentication-failure-url
,则可以使用authentication-failure-handler-ref
注入自定义AuthenticationFailureHandler
bean,您可以根据异常实现不同的行为。
答案 2 :(得分: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"%>
...