Spring Security - 自定义错误信息

时间 2021/5/28 15:33:09 加载中...

自定义错误信息

目前页面上的错误信息默认是英文的,我们只是通过字符串判断将其转换了一下,然而其它错误并没有处理。

  1. <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 支持语言本地化。
页面修改如下:

  1. <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 即可。

  1. @Component
  2. public class MyConf {
  3. @Bean
  4. public MessageSource messageSource() {
  5. ResourceBundleMessageSource source = new ResourceBundleMessageSource();
  6. //source.setBasenames("classpath:messages");
  7. source.setBasenames("messages");
  8. source.setUseCodeAsDefaultMessage(true);
  9. //source.setCacheSeconds(1);
  10. return source;
  11. }
  12. }

登录失败的错误信息为什么在 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);

  1. protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
  2. if (this.forwardToDestination) {
  3. request.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
  4. } else {
  5. HttpSession session = request.getSession(false);
  6. if (session != null || this.allowSessionCreation) {
  7. request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", exception);
  8. }
  9. }
  10. }

就里将异常信息保存在了 session 的 SPRING_SECURITY_LAST_EXCEPTION 属性中了。

扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/spring-security-custom-error-message.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。