如何根据我得到的错误自定义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
。
- 如何在GridLayout中调整JComponents的大小?
- 在txt File Java中查找字符串(或行)
- 使用MockMVC测试Spring MVC路由器
- Java StringTokenizer,空null标记
- Apache Tomcat无法加载web.xml – 连接超时
- writeAll(ResultSet res,Boolean b)opencsv方法在数据周围添加双引号
- 使用JSch执行的命令与SSH终端的行为不同(绕过确认提示消息“是/”否“)
- 如何在Spring MVC或Spring-Boot中返回不同类型的ResponseEntity
- Spring 4 MVC和Websockets – 没有合适的默认RequestUpgradeStrategy