如何基于邮件和使用spring Security的uid从LDAP验证用户?

时间:2016-08-01 06:25:00

标签: java spring security spring-boot ldap

我希望用户能够通过他的uid和邮件登录?如何使用我的Spring安全配置来实现这一目标?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin().passwordParameter("password");
    }

    @Configuration
    protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {

        @Autowired
        LdapContextSource contextSource;

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .ldapAuthentication()
                    .userDnPatterns("uid={0}")
                    .contextSource(contextSource);
        }
    }
}

在userDnPatterns中我可以指定另一个属性和uid吗?或者使用uid进行身份验证是标准的吗?

1 个答案:

答案 0 :(得分:3)

您需要使用自定义用户搜索过滤器。以下代码使用OR过滤器尝试将uid或邮件与用户在登录屏幕中输入的值进行匹配:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin().passwordParameter("password");
    }

    @Configuration
    protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {

        @Autowired
        LdapContextSource contextSource;

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .ldapAuthentication()
                    .userDnPatterns("uid={0}")
                    .userSearchFilter("(|(uid={0})(mail={0}))")
                    .contextSource(contextSource);
        }
    }
}