[英]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.