gat*_*r88 12 authentication exception-handling spring-security
我有一个使用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();
...
}
Run Code Online (Sandbox Code Playgroud)
我想在每个异常上发送cutom响应代码,例如404为UsernameNotFoundException,403为DisabledException等.现在我只在我的spring安全配置中有authentication-failure-url所以我在每个异常中重定向到authenticate ().
bar*_*ber 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");
}
}
Run Code Online (Sandbox Code Playgroud)
配置:
<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>
Run Code Online (Sandbox Code Playgroud)
Sha*_*eep 15
提供身份验证失败原因的详细信息通常是一个坏主意,因为它可以为攻击者提供有用的信息.例如,它可以允许他们探测有效的帐户名称.
如果您需要自定义内容,那么authentication-failure-url您可以使用authentication-failure-handler-ref注入自定义AuthenticationFailureHandlerbean来实现不同的行为,具体取决于异常.
在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>
Run Code Online (Sandbox Code Playgroud)
还包括以下标签库,以便正常工作
<%@ 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"%>
Run Code Online (Sandbox Code Playgroud)
...
| 归档时间: |
|
| 查看次数: |
32392 次 |
| 最近记录: |