ldap用户验证-用户名验证
使用用户名和密码来进行ldap验证,需要使用cn(用户名)、ou(组织)和dc(多个dc可以表示域名)等关键字。
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
/**
* This is a tool class for connecting to ldap.
* @author Jason
*/
public class CopyOfConnLDAP {
//store the connected information
private Hashtable env = null;
//ldap context
private LdapContext ctx = null;
//set some connected information
private String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private String PROVIDER_URL = "ldap://10.27.132.17:389";
private String SECURITY_AUTHENTICATION = "simple";
private String SECURITY_PRINCIPAL = "CN=视频会议组,OU=机关服务部,OU=信息技术服务中心,OU=集团公司机关,DC=CNPC,DC=COM,DC=CN";
private String SECURITY_CREDENTIALS = "sphy321";
public static void main(String[] args) {
CopyOfConnLDAP con=new CopyOfConnLDAP();
try {
LdapContext ctxs = con.connectLdap();
Attributes attrs = ctxs.getAttributes("CN=itest,OU=信息技术服务中心,OU=集团公司机关,DC=CNPC,DC=COM,DC=CN");
for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
Attribute attr = (Attribute) ae.next();
System.out.println("attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()));
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** Creates a new instance of ConnLDAP */
public CopyOfConnLDAP() {
env = new Hashtable();
}
/**
* Connect to ldap and initialize the ldap context.
* @throws javax.naming.NamingException If connect fail,throw this exception.
*/
public LdapContext connectLdap()throws NamingException{
//set the initializing information of the context
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
//set the URL of ldap server
env.put(Context.PROVIDER_URL, PROVIDER_URL);
//set the authentication mode
env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
//set user of AD
env.put(Context.SECURITY_PRINCIPAL, SECURITY_PRINCIPAL);
//set password of user
env.put(Context.SECURITY_CREDENTIALS, SECURITY_CREDENTIALS);
//initialize the ldap context
ctx = new InitialLdapContext(env,null);
return ctx;
}
public void closeContext() throws NamingException{
ctx.close();
}
/**
* Return the ldap context.
* @return Return the ldap context.
*/
public LdapContext getContext(){
return this.ctx;
}
}