Spring Security - 自定义错误信息
自定义错误信息
目前页面上的错误信息默认是英文的,我们只是通过字符串判断将其转换了一下,然而其它错误并没有处理。
<div style="color:red;" th:if="${param.error}" th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message == 'Bad credentials' ? '用户名或密码错误' : session.SPRING_SECURITY_LAST_EXCEPTION.message}"></div>
其实,Spring Security 支持语言本地化。
页面修改如下:
<div style="color:red;" th:if="${param.error}" th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.message}"></div>
然后,拷贝 spring-security-core-x.x.x.jar 包下的 messages_zh_CN.properties 文件到项目的 resources 目录下,然后注册 MessageSource 即可。
@Component
public class MyConf {
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
//source.setBasenames("classpath:messages");
source.setBasenames("messages");
source.setUseCodeAsDefaultMessage(true);
//source.setCacheSeconds(1);
return source;
}
}
登录失败的错误信息为什么在 session.SPRING_SECURITY_LAST_EXCEPTION.message 中?
我们输入一个错误的用户名和密码,查看下日志信息,在信息中有这样两句:
org.springframework.security.authentication.dao.DaoAuthenticationProvider [77] -| Failed to authenticate since password does not match stored value
org.springframework.security.web.DefaultRedirectStrategy [57] -| Redirecting to /account/login?error=true
我们定位到 DaoAuthenticationProvider.java 文件的 77 行。打上断点,调试。
返回的是一个 CredentialsExpiredException。调试到 ProviderManager.java 中
将异常赋值给了 lastException,在 AbstractAuthenticationProcessingFilter 的
unsuccessfulAuthentication 方法中有
this.failureHandler.onAuthenticationFailure(request, response, failed);
而 failureHandler 是 SimpleUrlAuthenticationFailureHandler 的,其 onAuthenticationFailure 中有
saveException(request, exception);
protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
if (this.forwardToDestination) {
request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
} else {
HttpSession session = request.getSession(false);
if (session != null || this.allowSessionCreation) {
request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
}
}
}
就里将异常信息保存在了 session 的 SPRING_SECURITY_LAST_EXCEPTION 属性中了。
*昵称:
*邮箱:
个人站点:
*想说的话: