Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://12.99.125.136:389/ou=用户,dc=xxx,dc=com" );
env.put(Context.SECURITY_PRINCIPAL, "账号");
env.put(Context.SECURITY_CREDENTIALS, "密 码");
DirContext ctx = null;
try {
ctx = new InitialDirContext(env);
NamingEnumeration result = null;
SearchControls controls = new SerachControls();
controls.setSearchScope(SearchControls.SUBSTREE_SCOPE);
result = ctx.search("","(sAMAccountName="+username+")",controls);
while(result.hasMore()){
SearchResult sr = (SearchResult) result.next();
Attributes attributes = sr.getAttributes();
Attribute attribute = attributes.get("cn");//拿储存在那个节点下的数据
String cn = attribute.get().toString();
}
这样都不需要去配置很多配置
如果是需要做登录验证的话:
ldap如果密码是不可见的话, Attributes attributes = sr.getAttributes();是拿不到的。
要叫给ldap server来进行验证,我们只能得到一个true或者false;
通过true 或者false来判断
String userDN="";
NamingEnumeration<?> en = ctx.search("","(sAMAccountName="+username+")",controls);
while(en!=null&&en.hasMoreElements()){
Object obj = en.nextElement();
if(obj instanceof SearchResult){
SearchResult si = (SearchResult )obj;
userDN +=si.getName();
userDN +=",ou=用户,dc=xxx,dc=com";
}
}
LdapContextSource contextSource = new LdapContextSource ();
contextSource.setUrl("ldap://12.11.223.555:389/");
contextSource.setUserDn("Ldap账号");
contextSource.setPassword("Ldap密码");
contextSource.setPooled(false);
contextSource.afterPropertiesSet();
ldapTemplate.setContextSource(contextSource);
//通过xx判断是否账号密码正确。
boolean xx = ldapTemplate.authenticate(userDN,"(objectclass=person)",password);