我有以下工作代码,可以用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, “[email protected]”);
env.put(Context.SECURITY_CREDENTIALS, "mypassword");
new InitialDirContext(env);
// authentication successful.
} catch (Exception exception) {
// authentication failed.
}
首先你应该把你的Connection信息写在一个配置文件里,比如一个ldap.yml文件,然后用这些属性注入一个ldaptemplate bean,这是一个propeties类。
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,这是一个propeties类。
@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 Annotations.这个注解允许Spring解析和注入协作Bean到你的Bean中。
@Autowired
LdapTemplate ldapTemplate;
使用ldapTemplate你可以像关系型数据库一样做CRUD.当然你也可以做认证的事情.这是我第一次在stackoverflow回答问题,欢迎大家指出我的错误。