Spring Boot进行LDAP身份验证的方法



我有以下工作代码,可以使用LDAP对用户进行身份验证。正如你所看到的,它非常简单。但是我怎么能用Spring Boot的方式做同样的事情呢?

try {
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, “ldaps://xxxxxxxx.abcgroup.xyz.com:636”);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); // fixed value
env.put(Context.SECURITY_PRINCIPAL, “myid@abcgroup.xyz.com”);
env.put(Context.SECURITY_CREDENTIALS, "mypassword");
new InitialDirContext(env);
// authentication successful.
} catch (Exception exception) {
// authentication failed.
}

首先,您应该将连接信息写入配置文件中,例如ldap.yml文件。

ldap:
url: ldap://XXXXXXX:389/
root: cn=root,dc=root,dc=com
userDn: cn=root,dc=root,dc=com
password: XXXXXX
baseDN: dc=root,dc=com
clean: true
pooled: false

然后使用这些属性注入ldaptemplatebean,这是一个属性类:

@ConfigurationProperties(prefix = "ldap")
public class LdapProperties {
private String url;
private String userDn;
private String password;
private String baseDN;
private String clean;
private String root;
private boolean pooled = false;
}

这是一个配置类:

@Configuration
@EnableConfigurationProperties({LdapProperties.class})
public class LdapConfiguration {
@Autowired
LdapProperties ldapProperties;
@Bean
public LdapTemplate ldapTemplate() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(ldapProperties.getUrl());
contextSource.setUserDn(ldapProperties.getUserDn());
contextSource.setPassword(ldapProperties.getPassword());
contextSource.setPooled(ldapProperties.getPooled());
contextSource.setBase(ldapProperties.getBaseDN());
contextSource.afterPropertiesSet();
return new LdapTemplate(contextSource);
}
}

然后您可以使用@Autowired Annotations。这个注释允许Spring解析协作bean并将其注入到您的bean中。

@Autowired
LdapTemplate ldapTemplate;

使用ldapTemplate,您可以像关系数据库一样进行CRUD。当然,您可以进行身份验证。这是我第一次在stackoverflow回答问题,我欢迎你指出我的错误。

最新更新