背景
業務需要將ad域裏面的信息加載 轉爲列表
Person.java 實體類
ADUtil.java 工具類
Person.java
import lombok.Data;
import lombok.ToString;
import org.springframework.ldap.odm.annotations.Attribute;
/**
* 這個方法是用來放你 ad域中的 屬性
* 自行填寫域中的屬性
* Attribute 這裏用於記錄名稱。 實際上這種方式沒有用上。
*/
@Data
@ToString
public class Person {
/**
* 主鍵
*/
@Attribute
private String personId;
/**
* 人員姓名
*/
@Attribute(name = "cn")
private String personName;
/**
* description 描述
*/
@Attribute(name = "description")
private String description;
/**
* objectCategory 對象類別
*/
@Attribute(name = "objectCategory")
private String objectCategory;
/**
* 郵箱
*/
@Attribute(name = "mail")
private String mail;
/**
* memberOf 成員
*/
@Attribute(name = "memberOf")
private String memberOf;
/**
* badPasswordTime 錯誤密碼的時間
*/
@Attribute(name = "badPasswordTime")
private String badPasswordTime;
/**
* objectClass 對象屬性
*/
@Attribute(name = "objectClass")
private String objectClass;
/**
* company 公司
*/
@Attribute(name = "company")
private String company;
/**
* name
*/
@Attribute(name = "name")
private String name;
/**
* sn 姓
*/
@Attribute(name = "sn")
private String sn;
/**
* telephoneNumber 座機
*/
@Attribute(name = "telephoneNumber")
private String telephoneNumber;
/**
* primaryGroupID 主要 組ID
*/
@Attribute(name = "primaryGroupID")
private String primaryGroupID;
/**
* lastLogon 最後登錄時間
*/
@Attribute(name = "lastLogon")
private String lastLogon;
/**
* lockoutTime 鎖定時間
*/
@Attribute(name = "lockoutTime")
private String lockoutTime;
/**
* physicalDeliveryOfficeName 實物交付辦公室名稱
*/
@Attribute(name = "physicalDeliveryOfficeName")
private String physicalDeliveryOfficeName;
/**
* msDS-RevealedDSAs ms DS公開的DS爲
*/
@Attribute(name = "msDS-RevealedDSAs")
private String msDSRevealedDSAs;
/**
* title 職位
*/
@Attribute(name = "title")
private String title;
/**
* logonCount 登錄次數
*/
@Attribute(name = "logonCount")
private String logonCount;
/**
* givenName 名
*/
@Attribute(name = "givenName")
private String givenName;
/**
* displayName 名稱
*/
@Attribute(name = "displayName")
private String displayName;
/**
* pwdLastSet 最後設置密碼時間
*/
@Attribute(name = "pwdLastSet")
private String pwdLastSet;
/**
* userPrincipalName 用戶主題名稱,用於登錄的名稱
*/
@Attribute(name = "userPrincipalName")
private String userPrincipalName;
/**
* department 部門
*/
@Attribute(name = "department")
private String department;
/**
* distinguishedName 專有名稱
*/
@Attribute(name = "distinguishedName")
private String distinguishedName;
/**
* manager 管理信息
*/
@Attribute(name = "manager")
private String manager;
/**
* sAMAccountName OP
*/
@Attribute(name = "sAMAccountName")
private String sAMAccountName;
}
ADUtil.java
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Optional;
public class ADUtil {
/**
* 連接 ad域
*
* @param adLdapIP
* @param port
* @param username
* @param password
* @return
*/
public static DirContext getDirContext(String adLdapIP, int port, String username, String password) {
Hashtable<String, String> env = new Hashtable<String, String>();
DirContext ctx = null;
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + adLdapIP + ":" + port);//AD域路徑和端口號 一般端口是389
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.REFERRAL, "throw");
env.put("java.naming.ldap.attributes.binary", "objectGUID");// objectGUID也可以指定爲其它屬性
try {
ctx = new InitialDirContext(env);// 初始化上下文
System.out.println("身份驗證成功!");
} catch (AuthenticationException e) {
System.out.println("身份驗證失敗!");
e.printStackTrace();
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域連接失敗!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("身份驗證未知異常!");
e.printStackTrace();
}
return ctx;
}
public ArrayList<Person> getByNameClose(DirContext ctx, String filter) {
return getByNameClose(ctx,filter);
}
/**
* 根據 filter關鍵字 連接並且獲取 AD 域信息放到 Person List
*
* @param ctx
* @param filter 過濾的關鍵字.如果關鍵字爲空就查詢所有
* @param close 是否關閉連接,true 關閉連接,flase 不關閉連接
* @return
*/
public ArrayList<Person> getByNameClose(DirContext ctx, String filter, Boolean close) {
ArrayList<Person> list = new ArrayList<>();
try {
//搜索控制器
SearchControls searchCtls = new SearchControls();
//設置搜索範圍 深度
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//LDAP搜索過濾器類,此處只獲取AD域用戶,所以條件爲用戶user或者person均可
//語法 https://www.cnblogs.com/chenne69163/p/12084086.html
//(&(objectCategory=person)(objectClass=user)(name=*))
// LDAP搜索過濾器類 cn=*name*模糊查詢 cn=name 相等查詢
//(|(name=*op1768*)(name=*op546*))
String searchFilter="(&(objectCategory=person)(objectClass=user)(name=*))";
if(!StringUtils.isBlank(filter)){
searchFilter = "(|(name=*" + filter + "*)" + "(mail=*" + filter + "*)" + ")";
}
//AD域節點結構
// 域節點
String searchBase = "OU=CPCNet User,DC=cpcnet,DC=local";
searchBase = "DC=cpcnet,DC=local";
String returnedAtts[] = {"objectClass", "sAMAccountName", "userPrincipalName", "displayName", "name", "mail",
"department", "telephoneNumber", "mobile"};
/* String returnedAtts[] = { "displayName","url", "employeeID", "mail",
"name", "userPrincipalName", "physicalDeliveryOfficeName",
"departmentNumber", "telephoneNumber", "homePhone",
"mobile", "department", "sAMAccountName", "whenChanged","mail"}; // 定製返回屬性*/
//設置指定返回的字段,不設置則返回全部
// searchCtls.setReturningAttributes(returnedAtts);
// 根據設置的域節點、過濾器類和搜索控制器搜索LDAP得到結果
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
// System.out.println("<<<::[" + sr.getName() + "]::>>>>");//返回格式一般是CN=xxxx,OU=xxxx
Attributes attrs = sr.getAttributes();//得到符合條件的屬性集
Person person = new Person();
person.setPersonName(get(attrs,"cn"));
person.setDescription(get(attrs,"description"));
person.setObjectCategory(get(attrs,"objectCategory"));
person.setMail(get(attrs,"mail"));
person.setMemberOf(get(attrs,"memberOf"));
person.setBadPasswordTime(get(attrs,"badPasswordTime"));
person.setObjectClass(get(attrs,"objectClass"));
person.setCompany(get(attrs,"company"));
person.setName(get(attrs,"name"));
person.setSn(get(attrs,"sn"));
person.setTelephoneNumber(get(attrs,"telephoneNumber"));
person.setPrimaryGroupID(get(attrs,"primaryGroupID"));
person.setLastLogon(get(attrs,"lastLogon"));
person.setLockoutTime(get(attrs,"lockoutTime"));
person.setPhysicalDeliveryOfficeName(get(attrs,"physicalDeliveryOfficeName"));
person.setMsDSRevealedDSAs(get(attrs,"msDSRevealedDSAs"));
person.setTitle(get(attrs,"title"));
person.setLogonCount(get(attrs,"logonCount"));
person.setGivenName(get(attrs,"description"));
person.setDisplayName(get(attrs,"givenName"));
person.setPwdLastSet(get(attrs,"pwdLastSet"));
person.setUserPrincipalName(get(attrs,"userPrincipalName"));
person.setDepartment(get(attrs,"department"));
person.setDistinguishedName(get(attrs,"distinguishedName"));
person.setManager(get(attrs,"manager"));
person.setSAMAccountName(get(attrs,"sAMAccountName"));
list.add(person);
}
if (close) {
closeDirContext(ctx);
}
return list;
} catch (NamingException e) {
e.printStackTrace();
System.err.println("Problem searching directory: " + e);
}
return list;
}
public String get(Attributes attrs,String attrID) throws NamingException {
return Optional.ofNullable(attrs.get((attrID))).isPresent() ? attrs.get(attrID).get().toString(): "";
}
public void closeDirContext(DirContext ctx){
try {
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
public void getRest() {
String adLdapIP = "10.180.4.249";
int port = 389;
String username = "[email protected]";//賬號
String password = "xxxxxx";//密碼
DirContext dirContext = getDirContext(adLdapIP, port, username, password);
//測試例子
String filter="op1768";
List<Person> list=getByNameClose(dirContext,filter,false);
System.out.println(JSONUtil.toJsonStr(list));
filter="movie";
List<Person> list1=getByNameClose(dirContext,filter,false);
System.out.println(JSONUtil.toJsonStr(list1));
list=getByNameClose(dirContext,null,false);
System.out.println(JSONUtil.toJsonStr(list));
closeDirContext(dirContext);
}
public static void main(String[] args) {
ADUtil adUtil=new ADUtil();
adUtil.getRest();
}
}