且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-26 22:16:38

我觉得我需要使用 LdapContextSource 的实例才能实现这一点(因为它方便地有一个 setReferral 方法),但我对细节有点挣扎。 论坛帖子 spring.io给了我足够的时间,看起来我现在已经有了工作。

I had the feeling I'd need to use an instance of LdapContextSource to make this happen (since it conveniently has a setReferral method), but I struggled a bit with the details. A forum post on spring.io gave me enough to go on, and it looks like I now have things working.

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

It's not clear to me if there are any significant flaws with what I'm doing here, but it seems to work, so hopefully this will be helpful to someone else in the future:

@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);
        }
    }
}