![](/img/trans.png)
[英]How to catch the exceptions thrown by spring security matchers?
[英]How to handle run time exceptions thrown by Spring Security AuthenticationProviders?
如何处理Spring Security Authentication Providers抛出的运行时异常? 我正在使用Spring Boot 1.4.2,但我觉得这也适用于经典的Spring应用程序。
假设我有一个ActiveDirectoryLdapAuthenticationProvider
配置为根据我的公司AD对用户进行身份验证。 当身份验证因验证失败而导致身份验证失败时,这一切都适用于Spring Security(抛出AuthenticationException
,由Spring安全机制正确处理=应用程序返回登录屏幕并显示身份验证错误)。
但是,有时候,AD会暂时关闭,而是抛出org.springframework.ldap.CommunicationException
。 此异常是运行时异常,因此不会被Spring的安全机制捕获,因为它不会扩展AuthenticationException
。
在这种情况下会发生的是,应用程序被重定向到默认错误页面(这是/错误)。 我想要做的是仍然显示带有自定义消息的登录屏幕。
如果我创造了类似的东西,我发现我可以做到这一点
public class ActiveDirectoryLdapExtendedAuthenticationProvider implements AuthenticationProvider {
private final ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider;
public ActiveDirectoryLdapExtendedAuthenticationProvider(ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider) {
this.adAuthenticationProvider = adAuthenticationProvider;
}
@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {
Authentication auth = null;
try {
auth = adAuthenticationProvider.authenticate(a);
}
catch(CommunicationException communicationException) {
throw new AuthenticationServiceException("Could not reach User Directory. Please try again in a few minutes");
}
return auth;
}
这有效,但我觉得必须有更好的方法。
我已经尝试创建一个ControllerAdvice
注释类,但它不会被POST调用以由Spring Security登录。 我想这是因为POST是由Spring安全过滤器处理的,它是Servlet过滤器,位于主要的Spring MVC调度程序servlet之上。
我还尝试创建一个SimpleMappingExceptionResolver
来处理CommunicationException
并重定向到登录页面,但这也不起作用,因为我的SimpleMappingExceptionResolver
也没有被调用。
我提出的另一个解决方法是在错误页面本身处理异常,例如(使用Thymeleaf)
<div class="container error" th:switch="${exception}">
<span th:case="'org.springframework.ldap.CommunicationException'">Error communicating with User Directory. Please try again in a few minutes</span>
<span th:case="*">An unexpected error has occurred</span>
</div>
我仍然觉得应该有更好的方法。 如何配置DispatcherServlet以确保将CommunicationException重定向到/ login控制器,而不是错误页面? 或者更一般地说......如何在登录阶段显示登录阶段的任何异常?
经验丰富的相同问题并解决了它创建自定义Spring AuthenticationFailureHandler 。 它通过在自定义AuthenticationProvider类中抛出BadCredentialsException来捕获错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.