使用Spring Security和JavaConfig进行身份验证时出现PartialResultException

时间:2014-11-06 23:51:54

标签: java spring-security spring-ldap

我目前正在使用Spring Boot创建一个新的Web应用程序,并开始集成Spring Security进行身份验证。在成功遵循基于Spring Boot的LDAP tutorial之后,我想将基于JavaConfig的配置指向我的Active Directory实例。

我的应用程序现在按预期处理错误的凭据,但现在有效的凭据会导致

javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name ''

这是一个常见问题 - 有number of places遇到此问题。解决方案似乎是将Context.REFERRAL设置为“follow”,但我找不到任何指示如何使用JavaConfig设置该选项的文档。这是我唯一可以恢复基于XML的配置吗?看起来Spring正在将开发人员推向JavaConfig,所以如果可能的话,我想避免混合使用这两种方法。

以下是我的安全配置:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest()
                .fullyAuthenticated().and().formLogin();
    }

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.ldapAuthentication()
                .userSearchBase("")
                .userSearchFilter("(&(cn={0}))").contextSource()
                .managerDn("<username>")
                .managerPassword("<password>")
                .url("ldap://<url>");
        }
    }
}

1 个答案:

答案 0 :(得分:14)

我觉得我需要使用LdapContextSource的实例来实现这一点(因为它方便地使用setReferral方法),但我对细节进行了一些努力。 spring.io上的一个forum post给了我足够的时间,看起来我现在已经有了工作。

我不清楚我在这里做的是否存在任何重大缺陷,但似乎有效,所以希望这对未来的其他人有所帮助:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest()
                .fullyAuthenticated().and().formLogin();
    }

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {              
            DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://<url>");
            contextSource.setUserDn("<username>");
            contextSource.setPassword("<password>");
            contextSource.setReferral("follow"); 
            contextSource.afterPropertiesSet();

            LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth.ldapAuthentication();

            ldapAuthenticationProviderConfigurer
                .userSearchFilter("(&(cn={0}))")
                .userSearchBase("")
                .contextSource(contextSource);
        }
    }
}