Spring Boot Security / LDAP与用户凭证直接绑定

时间:2019-04-29 16:13:05

标签: spring-boot spring-security spring-ldap spring-security-ldap

是否可以使用的凭据通过Spring Boot Security / LDAP来对用户进行身份验证,而不是先绑定某些功能凭据,然后再尝试绑定用户?

我不想像下面那样使用managerDn和managerPassword:

auth.ldapAuthentication()
    .userSearchBase("")
    .userSearchFilter("(samAccountName={0})")
    .contextSource()
        .url("ldap://<url>/<root>")
        .managerDn("functionUser")
        .managerPassword("password")

1 个答案:

答案 0 :(得分:0)

在我的应用程序中,我实现了自定义UsernamePasswordAuthenticationProvider,以根据用户记录中设置的标志针对自己的数据库或远程LDAP对用户进行身份验证。

要针对远程LDAP进行身份验证,我使用了以下代码。它可能对我有用,也许对您也有用:)。

protected void validateCredentialsAgainstActiveDirectory(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {
    try {
        LdapConfiguration config  = ...;

        /*
         * We will create a new LDAP connection on the fly each time an AD user logs in.
         * Hence we must disable caching properties to avoid NullPointerException later
         * in AbstractContextSource.getAuthenticatedEnv().
         * 
         */
        DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(config.getUrl());
        contextSource.setCacheEnvironmentProperties(false);

        // Authenticate the user against the pre-configured userDnTemplate
        BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource);
        bindAuthenticator.setUserDnPatterns(new String[] { config.getUserDnTemplate() });
        bindAuthenticator.authenticate(authentication);

    } catch (BadCredentialsException ex) {
        // Catch downstream exception to return our own message
        throw new BadCredentialsException(SpringUtils.getMessage("security.login.error.bad-credentials"));

    }
}

仅供参考,LdapConfiguration是我自己的自定义类,用于从.yml文件中读取配置。在此文件中,我如下配置了LDAP服务器的url和DN模板。您需要进行更改以适合您的环境。

url: ldap://10.10.10.231:10389/dc=mycompany,dc=com
userDnTemplate: uid={0},ou=people

也不要忘记在项目中导入必要的依赖项。

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.ldap</groupId>
  <artifactId>spring-ldap-core</artifactId>
</dependency>