准备工作:使用openldap搭建server 过程略
名词
DN = Distinguished Name
DC = Domain Component
OU = Organization Unit
CN = Common Name
RDN = Relative DN
UID = User ID
1.初始化
protected static int init() {
int flag = 0;
try {
ldapHost = "192.168.1.1";
ldapNameAll = "ldap://" + ldapHost;
ldapPort = 389;
rootEntry ="dc=sysu,dc=edu,dc=cn";
rootdn = "uid=rgsam,ou=hosts,dc=sysu,dc=edu,dc=cn";
rootpw = "111";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapNameAll + ":" + ldapPort);
env.put("com.sun.jndi.ldap.connect.timeout", "3000");
if (rootdn != null && !rootdn.equals("") && rootpw != null && !rootpw.equals("")) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, rootdn);
env.put(Context.SECURITY_CREDENTIALS, rootpw);
}
ctx = new InitialDirContext(env);
} catch (Exception e) {
flag = -1;
}
//返回初始化是否成功的标志位
return flag;
}
2.遍历查询
protected static int getProcessResultBatch(DirContext ctx,int limit) {
try {
String userObjectClass = "eduPerson";
String userIdAttrName ="uid";
String userPwdAttrName = "userPassword";
String userAccessTimeAttrName ="radiusExpiration";
String ldapFilter = "";
String ldapPassword = null;
String ldapAccessTime = null;
String[] attrList = null;
String rootEntry="dc=sysu,dc=edu,dc=cn";
String searchFilter = "(&(objectClass=" + userObjectClass + "))";
//Filter可自定义,一旦定义了Filter则ObjectClass就无效了
if (ldapFilter != null && !ldapFilter.equals("")) {
//searchFilter = StringUtil.str_replace(ldapFilter, "%{User-Name}", userId);
}
attrList = new String[] {userPwdAttrName, userAccessTimeAttrName};
String dn = null;
NamingEnumeration ne = null;
try {
SearchControls controls = new SearchControls(SearchControls.SUBTREE_SCOPE, limit, 0, attrList, false, false);
ne = ctx.search(rootEntry, searchFilter, controls);
} catch (Exception e) {
return RESULT_ERR_CONNECT;
}
while(ne.hasMore()) {
SearchResult sr = (SearchResult)ne.next();
Attributes attrs = sr.getAttributes();
Attribute passwordAttr = attrs.get(userPwdAttrName);
ldapPassword = new String((byte[]) passwordAttr.get());
if(ldapPassword == null){
return RESULT_ERR_PASSWORD;
}
Attribute accessTimeAttr = attrs.get(userAccessTimeAttrName);
ldapAccessTime = (String)accessTimeAttr.get();
dn = sr.getNameInNamespace();
System.out.println(dn.toString());
}
} catch (Exception e) {
return RESULT_ERR_CONNECT;
}
return RESULT_SUCCESS;
}
3.测试程序
int ret=init();
if(ret==0){
System.out.println("LDAP初始化成功");
}else{
System.out.println("LDAP初始化失败");
}
int result=getProcessResultBatch(ctx,100);
if(result==RESULT_SUCCESS){
System.out.println("RESULT_SUCCESS");
}else if(result==RESULT_ERR_CONNECT){
// System.out.println("RESULT_ERR_CONNECT");
}else if(result==RESULT_ERR_NOUSER){
System.out.println("RESULT_ERR_NOUSER");
}else if(result==RESULT_ERR_PASSWORD){
System.out.println("RESULT_ERR_PASSWORD");
}else{
System.out.println("RESULT_OTHER");
}
微信公众号: 架构师日常笔记 欢迎关注!