java - Spring Security - AD 服务器离线时无法捕获 LDAP 异常

标签 java spring-security

我已经在我们的应用程序中启动并运行了 Spring Security LDAP 身份验证,除了一方面之外,一切都运行顺利。那是 如果 AD 服务器恰好离线或无法联系,则会抛出 org.springframework.ldap.CommunicationException 。然而这个异常未被捕获 并作为 Tomcat HTTP 500 错误页面传播回客户端,包括堆栈跟踪(如下所示)。

我正在使用带有 Spring Security 4.0.1、Java 8 和 Tomcat 7.0.42 的 java 配置。

springframework.ldap.CommunicationException: localhost:389; nested exception is javax.naming.CommunicationException: localhost:389 [Root exception is java.net.ConnectException: Connection refused: connect]
org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.bindAsUser(ActiveDirectoryLdapAuthenticationProvider.java:211)
org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.doAuthentication(ActiveDirectoryLdapAuthenticationProvider.java:143)
org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.authenticate(AbstractLdapAuthenticationProvider.java:82)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
... other frames omitted

此异常跟踪中没有任何代码,甚至在堆栈的更上方(为简洁起见,我将其省略,因为它只是 Servlet 过滤器链)。

通常,在这种情况下,我只会子类化 Spring ActiveDirectoryLdapAuthenticationProvider 类,并在该派生类调用中 try/catch 中的基类 doAuthentication() 方法并从那里开始。不幸的是 ActiveDirectoryLdapAuthenticationProvider 已声明 作为最终决定,所以我不能这样做。

我尝试了一些其他方法,试图在我的代码中捕获该异常。这些是

  1. 在 formLogin 配置中添加了身份验证失败处理程序,如下所示。但是当抛出异常时,这不会被调用,它只是看起来 触发基于身份验证的异常,

        ...
        .formLogin()            
            .usernameParameter("j_username")
            .passwordParameter("j_password")            
            .loginPage("/login.jsp")
            .loginProcessingUrl("/j_spring_security_check")         
            .successHandler(authenticationSuccessHandler())
            .failureHandler(authenticationFailureHandler())
        .and()
        ...
    
  2. 在我的 SecurityConfig.java 文件中使用以下代码为任何未经身份验证的请求设置authenticationEndpoint,

        ...
        .formLogin()            
            .usernameParameter("j_username")
            .passwordParameter("j_password")            
            .loginPage("/login.jsp")
            .loginProcessingUrl("/j_spring_security_check")         
            .successHandler(authenticationSuccessHandler())
        .and()
        .exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint())
        ...
    

其中 myAuthenticationEntryPoint() 方法是一个 @Bean 注解的方法,它仅返回一个新的 Http403ForbiddenEntryPoint。但这又没有被调用 我仍然从配置的身份验证入口点收到 HTTP 500 错误而不是 403。

Spring Security源码中实际抛出异常的方法如下所示:

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String,String> env = new Hashtable<String,String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

对于无法联系 AD 服务器的情况,代码将进入异常处理程序中的 else 子句,我们会得到一个基于 Ldap 的异常。据我所知,这意味着没有调用任何“正常”身份验证失败处理程序。

我发现捕获此异常的唯一方法是“ fork ”ActiveDirectoryLdapAuthenticationProvider 类,即将其内容剪切并粘贴到新类中并从中派生一个类。这样做按预期工作,我可以在 try/catch 中捕获异常。但我真的不想选择这个选项,因为它只是一个 hack。

有人遇到过类似的情况并找到了更优雅的解决方案吗?我忍不住认为必须有一种方法来处理期间的所有异常 登录过程,不仅仅是基于身份验证的过程,但我一直无法找到一种方法来做到这一点。

最佳答案

您刚刚在 @kpentchev 答案中写了这个:

My expected behaviour when this exception is thrown is that I can catch it and return the user to login page with a suitable error. Rather than the use just seeing the blue Tomcat 500 error page with the exception trace.

如果您只是想“阻止”默认的 Tomcat 错误页面,以便攻击者或用户无法看到有关您服务器的重要信息,您可以将其放入 web.xml 中:

<error-page> 
<error-code>500</error-code> 
<location>/error.jsp</location> 
</error-page>

之后,在 error.jsp 页面中,您可以使用以下命令检查异常:

Throwable throwable = (Throwable) request
                .getAttribute("javax.servlet.error.exception");

如果 throwable 是 CommunicationException.class 的实例,则将用户重定向到登录页面

关于java - Spring Security - AD 服务器离线时无法捕获 LDAP 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32818144/

相关文章:

java - Tomcat trowing 无效的生命周期转换

Java从windows机器远程访问linux机器

grails - Grails,无法在spring-security-core中获得角色类的实例

spring-mvc - Spring Security 拦截 url 模式不起作用

java - 如何制作透明布局?

java - 我可以对具有 'Z' 和 '+1:00' 后缀的日期使用一种 SimpleDateFormat 模式吗?

java - 使用 javassist 创建类并使其可用

java - 实现接口(interface)时未创建带有 @Secured 注释的类

java - 无法找到对象标识 'org.springframework.security.acls.domain.ObjectIdentityImpl 的 ACL 信息

java - Spring HttpSecurity 覆盖响应头