如何根据我得到的错误自定义SPRING_SECURITY_LAST_EXCEPTION.message

我用Spring Security制作了一个登录系统。 这是我的spring-security.xml

...      ... 

因为我有这行authentication-failure-url="/login?error=true"我知道如果error'true'则会出现错误:它可能是“ 凭据错误”或“ 超出最大会话数 ”。但我知道我想知道哪个错误真的发生了?

有没有办法在java类(@controller)中知道Spring给我的错误,以便自定义这些错误消息?

我发现这个解决方案,它似乎工作。

扩展SimpleUrlAuthenticationFailureHandler您可以将用户发送到不同的页面,并打印所需的消息。

我的主要目标不是“覆盖” SPRING_SECURITY_LAST_EXCEPTION.message而是根据Spring安全性给我的各种错误自定义错误消息。

web.xml中

   org.springframework.security.web.session.HttpSessionEventPublisher  

security-config.xml(只是一些代码)

会话管理

     

form-login ,您可以在其中调用自己的AuthenticationFailureHandler(customFailureHandler)

   

您自己的AuthenticationFailureHandler的bean

   

这是实现SimpleUrlAuthenticationFailureHandler的类

 import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.authentication.session.SessionAuthenticationException; public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if(exception.getClass().isAssignableFrom(BadCredentialsException.class)) { setDefaultFailureUrl("/url1"); } else if (exception.getClass().isAssignableFrom(DisabledException.class)) { setDefaultFailureUrl("/url2"); } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) { setDefaultFailureUrl("/url3"); } super.onAuthenticationFailure(request, response, exception); } } 

希望这可以帮助别人。

您需要使用authentication-failure-handler-ref而不是authentication-failure-url来引用您需要创建的故障处理程序bean,并将不同的URL(或不同的params映射到同一URL)映射到不同类型的exception。

      /url1 /url2 /url3     

文档中提到了许多其他exception。 请参考文档

编辑:

同样的例外情况是,抛出SessionAuthenticationException通常是因为同一用户已超过允许并发的会话数。 但这仅在容器级别,如果您有多个容器,则无法工作。

       

这是一个老问题,但由于标记为正确的答案实际上包含一个令人讨厌的微妙错误,应该注意正确的解决方案是使用内置的ExceptionMappingAuthenticationFailureHandler而不是@mdp的答案中建议的CustomAuthenticationFailureHandler