我有以下工作代码可以通过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.
}
答案 0 :(得分:0)
首先,您应该将连接信息写入配置文件(例如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
然后使用这些属性注入ldaptemplate bean,这是一个属性类:
@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类:
@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批注。此批注使Spring能够解析协作豆并将其注入到您的bean中。
@Autowired
LdapTemplate ldapTemplate;
使用ldapTemplate,您可以像关系数据库一样执行CRUD。当然,您可以执行身份验证。 这是我第一次在stackoverflow中回答问题,欢迎您指出我的错误。