Spring Security - 自定义登录错误消息

时间:2016-12-30 23:43:08

标签: spring spring-security

我有两种不同类型的登录错误:

  • 用户/ pw
  • 不正确
  • IP阻止了太多次尝试

现在Spring在两种情况下都将用户转发到www.site.com/login?error。如何自定义登录行为,以便根据具体情况将用户转发到error1或error2?这种前向行为似乎没有在任何地方明确声明,我找不到任何关于此的文档。

1 个答案:

答案 0 :(得分:1)

您必须实现自定义AuthenticationFailureHandler,请参阅: Spring security authenticate exceptions handling

如果您只想将用户重定向到error1或error2,那么您的实现可能只是一个简单的重定向方法:

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)) {
     response.sendRedirect("error1")
   } else if (exception.getClass().isAssignableFrom(LockedException.class)) {
     response.sendRedirect("error2")
   }
 }
}