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



有没有办法使用凭据对 Spring 启动安全性/LDAP 对用户进行身份验证,而不是先绑定某些功能凭据,然后尝试绑定用户?

我不想像以下情况下使用managerDnmanagerPassword

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

在我的应用程序中,我实现了一个自定义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>

最新更新