小编min*_*lkr的帖子

如何处理 Spring Security AuthenticationProviders 抛出的运行时异常?

如何处理 Spring Security Authentication Providers 抛出的运行时异常?我使用的是 Spring Boot 1.4.2,但我觉得这也适用于经典的 Spring 应用程序。

假设我有一个ActiveDirectoryLdapAuthenticationProvider配置来根据我的公司 AD 对用户进行身份验证。当由于凭据错误导致身份验证失败时,Spring Security 一切都很好(AuthenticationException抛出一个 由 Spring Security 机制正确处理的问题 = 应用程序返回登录屏幕并且可以显示身份验证错误)。

然而,有时,AD 会暂时关闭,org.springframework.ldap.CommunicationException而是抛出a 。此异常是运行时异常,因此不会被 Spring 的安全机制捕获,因为它没有扩展AuthenticationException

在这种情况下,应用程序被重定向到默认错误页面(即 /error)。我想要做的是仍然显示带有自定义消息的登录屏幕。

我发现我可以做到这一点,如果我创建类似的东西

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 …
Run Code Online (Sandbox Code Playgroud)

java spring exception-handling spring-security spring-boot

5
推荐指数
1
解决办法
1658
查看次数