java AD域连接测试及获取所有用户信息(可去掉禁用账户)
(AD域测试需要自己拼接ip 端口 账号 密码等内容,然后获取AD域上账户信息,拿到自己想要的数据)
postman自测OK
代码以下:
/**
* 测试连接
*
* @param request
* @return
*/
@PostMapping(value = "/test")
@ResponseBody
@ApiOperation("测试连接")
@ControllerLog(description = "测试连接")
public ResponseResult test(@RequestBody Map<String, Object> request) {
return externalConfigService.testConnection(request);
}
@Override
public ResponseResult testConnection(Map<String, Object> request) {
boolean testConnect = ADUtil.testConnect(request);
return ResponseResult.general(200, testConnect ? "测试连接成功" : "测试连接失败", testConnect ? "YES" : "NO");
}
@Override
public ResponseResult testConnection(Map<String, Object> request) {
boolean testConnect = ADUtil.testConnect(request);
return ResponseResult.general(200, testConnect ? "测试连接成功" : "测试连接失败", testConnect ? "YES" : "NO");
}
import com.alibaba.fastjson.JSONObject;
import com.model.AdDepartment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;
public class ADUtil {
private static Logger LOG = LoggerFactory.getLogger(ADUtil.class);
public static NamingEnumeration<SearchResult> getSearchResult(LdapContext ctx, String searchFilter, String searchBase) throws NamingException {
//搜索控制器
SearchControls searchCtls = new SearchControls();
//创建搜索控制器
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String returnedAtts[] = {"canonicalName", "distinguishedName", "id",
"name", "userPrincipalName", "departmentNumber", "telephoneNumber", "homePhone",
"mobile", "department", "sAMAccountName", "whenChanged", "user", "userAccountControl"}; // 定制返回属性
searchCtls.setReturningAttributes(returnedAtts);
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls);
return answer;
}
// 连接ad域
public static LdapContext getContext(Properties env) throws NamingException {
LdapContext ctx = new InitialLdapContext(env, null);
return ctx;
}
public static String getTreeAdDepartment(Properties env, String domain, String searchBase) {
LdapContext ctx;
String result = "";
try {
ctx = getContext(env);
TreeSet<AdDepartment> as = getAdDepartment(ctx, searchBase);
System.out.println(getTreeAdDepartment(as, domain));
if (ctx != null) {
ctx.close();
}
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(getTreeAdDepartment(as, domain)));
return jsonObject.toString();
} catch (NamingException e) {
e.printStackTrace();
}
return result;
}
public static AdDepartment getTreeAdDepartment(TreeSet<AdDepartment> treeSet, String domain) {
AdDepartment root = new AdDepartment();
root.setName(domain);
root.setcName(domain);
for (AdDepartment ad : treeSet) {
AdDepartment parentAdDepartment = null;
if ((parentAdDepartment = root.getParentAdDepartmentBycName(ad.getcName())) != null) {
parentAdDepartment.addChildren(ad);
} else {
root.addChildren(ad);
}
}
return root;
}
// 获取部门列表
public static TreeSet<AdDepartment> getAdDepartment(LdapContext ctx, String searchBase) throws NamingException {
//LDAP搜索过滤器类,此处只获取AD域用户,所以条件为用户user或者person均可
String searchFilter = "objectClass=User";
//AD域节点结构
NamingEnumeration<SearchResult> answer = getSearchResult(ctx, searchFilter, searchBase);
TreeSet<AdDepartment> treeSet = new TreeSet<AdDepartment>();
while (answer.hasMoreElements()) {
SearchResult sr = answer.next();
AdDepartment adDepartment = new AdDepartment();
// 是否禁用账户,过滤掉禁用账户
if (isDisableAccount(sr)) {
continue;
}
adDepartment.setName(getAttrValue(sr, "name"));
adDepartment.setcName(getAttrValue(sr, "canonicalName"));
adDepartment.setDistinguishedName(getAttrValue(sr, "distinguishedName"));
treeSet.add(adDepartment);
}
return treeSet;
}
private static boolean isDisableAccount(SearchResult sr) throws NamingException {
Attributes Attrs = sr.getAttributes();
Attribute attr = Attrs.get("userAccountControl");
if (attr != null) {
String control = Integer.toBinaryString(Integer.valueOf((String) attr.get()));
if ("1".equals(control.substring(control.length() - 2, control.length() - 1))) {
return true;
}
}
return false;
}
/**
* 获取属性值
*
* @param sr
* @param attr
* @return
* @throws NamingException
*/
public static String getAttrValue(SearchResult sr, String attr) throws NamingException {
Attributes Attrs = sr.getAttributes();
if (Attrs.get(attr) == null) {
return null;
}
return Attrs.get(attr).getAll().next().toString();
}
private static final String SUN_JNDI_PROVIDER = "com.sun.jndi.ldap.LdapCtxFactory";
/**
* 测试连接
*
* @param request
* @return
*/
public static boolean testConnect(Map<String, Object> request) {
boolean connectFlag = false;
String ip = request.get("serverIp").toString();
String port = request.get("serverPort").toString();
String domain = request.get("serverDomain").toString();
String uName = request.get("loginName").toString();
String uPassword = request.get("loginPassword").toString();
String URL = "ldap://" + ip + ":" + port;
if (!LogonUtil.ping(ip)) {
return false;
}
Hashtable<String, String> env = new Hashtable<String, String>();
//用户名称,cn,ou,dc 分别:用户,组,域
env.put(Context.SECURITY_PRINCIPAL, uName);
//用户密码 cn 的密码
env.put(Context.SECURITY_CREDENTIALS, uPassword);
//url 格式:协议://ip:端口/组,域 ,直接连接到域或者组上面
env.put(Context.PROVIDER_URL, URL);
//LDAP 工厂
env.put(Context.INITIAL_CONTEXT_FACTORY, SUN_JNDI_PROVIDER);
//验证的类型 "none", "simple", "strong"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
connectFlag = ctx != null;
} catch (NamingException e) {
LOG.info("testConnect false");
}
return connectFlag;
}
public class AdDepartment implements Comparable<AdDepartment>{
private String id;
private String name;
private String cName;
private String distinguishedName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public String getDistinguishedName() {
return distinguishedName;
}
public void setDistinguishedName(String distinguishedName) {
this.distinguishedName = distinguishedName;
}
public List<AdDepartment> getChildren() {
return children;
}
public void setChildren(List<AdDepartment> children) {
this.children = children;
}
private List<AdDepartment> children = new ArrayList<AdDepartment>();
public AdDepartment getAdDepartmentBycName(String cName) {
if (this.cName.equals(cName) ) {
return this;
}else{
for (AdDepartment adDepartment : children) {
AdDepartment adDepartment1 =null;
if ((adDepartment1 = adDepartment.getAdDepartmentBycName(cName)) != null) {
return adDepartment1;
}
}
}
return null;
}
public AdDepartment getParentAdDepartmentBycName(String cName) {
int index;
AdDepartment adDepartment = null;
while ((index = cName.lastIndexOf("/")) != -1) {
cName = cName.substring(0, index);
adDepartment = getAdDepartmentBycName(cName);
if (adDepartment != null) {
return adDepartment;
}
}
return adDepartment;
}
public int compareTo(AdDepartment o) {
return cName.length() - o.getcName().length();
}
public void addChildren(AdDepartment adDepartment) {
this.children.add(adDepartment);
}
@Override
public String toString() {
return "AdDepartment{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", cName='" + cName + '\'' +
", distinguishedName='" + distinguishedName + '\'' +
", children=" + children +
'}';
}
}
public void updateUsersMsg(Integer type, Map<String, Object> map) {
String ip = map.get("ip").toString();
String port = map.get("port").toString();
String domain = map.get("domain").toString();
String uName = map.get("uName").toString();
String uPassword = map.get("uPassword").toString();
String URL = "ldap://" + ip + ":" + port;
Properties env = new Properties();// 实例化一个Env
// LDAP 服务器的 URL 地址,
env.put(Context.SECURITY_AUTHENTICATION, "simple");// LDAP访问安全级别(none,simple,strong),一种模式,这么写就行
env.put(Context.SECURITY_PRINCIPAL, uName); // 用户名
env.put(Context.SECURITY_CREDENTIALS, uPassword);// 密码
env.put(Context.INITIAL_CONTEXT_FACTORY, SUN_JNDI_PROVIDER);// LDAP工厂类
env.put(Context.PROVIDER_URL, URL);// Url
LdapContext ctx;
// 所有数据,解析入库
String resultStr = "";
String sDomain = "";
if (domain.indexOf("@") == -1)
sDomain = "@" + domain;
String sB1 = sDomain.substring(1, sDomain.indexOf("."));
String sB2 = sDomain.substring(sDomain.indexOf(".") + 1, sDomain.length());
try {
ctx = ADUtil.getContext(env);
String searchBase = "DC=" + sB1 + ",DC=" + sB2;
resultStr = ADUtil.getTreeAdDepartment(env, domain, searchBase);
} catch (NamingException e) {
e.printStackTrace();
}
Map<String, Object> resultStrMap = (Map<String, Object>) JSONObject.parseObject(resultStr, Map.class);
List<Object> children = JSONObject.parseObject(JSONObject.toJSONString(resultStrMap.get("children")), List.class);
// children为获取到的用户数据
}
}
以上