瀏覽代碼

Ldap同步组织单位 同步人员 修改登录接口实现AD域控登录验证

Min 2 年之前
父節點
當前提交
07bfa2f192

+ 2 - 0
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/PlatformStartApplication.java

@@ -23,6 +23,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
 public class PlatformStartApplication {
     public static void main(String[] args) {
         SpringApplication.run(PlatformStartApplication.class, args);
+        //ldap ssl链接很关键的
+        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification","true");
     }
 
     //防止存入redis数据后乱码

+ 5 - 3
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/config/LdapConfig.java

@@ -14,15 +14,17 @@ public class LdapConfig {
     private String userName;
     @Value("${spring.ldap.password}")
     private String passWord;
-    @Value("${spring.ldap.base}")
-    private String base;
+    @Value("${spring.ldap.base.dcFirst}")
+    private String dcFirst;
+    @Value("${spring.ldap.base.dcSecond}")
+    private String dcSecond;
 
 
 
     @Bean
     public LdapContextSource ldapContextSource(){
         LdapContextSource source = new LdapContextSource();
-        source.setBase(base);
+        source.setBase("DC="+dcFirst+",DC="+dcSecond);
         source.setUrl(ldapUrl);
         source.setPassword(passWord);
         source.setUserDn(userName);

+ 149 - 12
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/controller/UserController.java

@@ -1,14 +1,20 @@
 package com.management.platform.controller;
 
 
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.management.platform.entity.FeishuInfo;
-import com.management.platform.entity.User;
-import com.management.platform.entity.UserCustom;
-import com.management.platform.mapper.UserCustomMapper;
+import com.management.platform.constant.Constant;
+import com.management.platform.entity.*;
+import com.management.platform.mapper.*;
 import com.management.platform.service.FeishuInfoService;
+import com.management.platform.service.SysRoleService;
 import com.management.platform.service.UserService;
+import com.management.platform.util.ColorUtil;
 import com.management.platform.util.HttpRespMsg;
+import com.management.platform.util.MD5Util;
+import com.management.platform.util.SnowFlake;
+import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.ldap.core.LdapTemplate;
 import org.springframework.ldap.filter.EqualsFilter;
@@ -19,11 +25,11 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import javax.naming.NamingException;
 import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.time.LocalDateTime;
+import java.util.*;
+import java.util.stream.Collectors;
 
 /**
  * <p>
@@ -51,6 +57,21 @@ public class UserController {
     @Resource
     private UserCustomMapper userCustomMapper;
 
+    @Resource
+    private CompanyMapper companyMapper;
+    @Resource
+    private TimeTypeMapper timeTypeMapper;
+    @Resource
+    private SysRoleService sysRoleService;
+    @Resource
+    private ProjectBasecostSettingMapper projectBasecostSettingMapper;
+    @Resource
+    private CompanyReportMapper companyReportMapper;
+    @Resource
+    private DepartmentMapper departmentMapper;
+    @Resource
+    private SysRoleMapper sysRoleMapper;
+
     /**
      * 登录网页端
      * username 用户名
@@ -307,14 +328,130 @@ public class UserController {
     }
 
 
-    @RequestMapping(value = "/testLdap4", method = RequestMethod.GET)
-    public HttpRespMsg testLdap4(@RequestParam String username, @RequestParam String passWord) {
-        EqualsFilter filter = new EqualsFilter("sAMAccountName", username);
+    @RequestMapping(value = "/loginForAd", method = RequestMethod.GET)
+    public HttpRespMsg loginForAd(@RequestParam String username, @RequestParam String passWord) {
+        HttpRespMsg httpRespMsg=new HttpRespMsg();
+        int i = username.indexOf("@");
+        String substring = username.substring(0, i);
+        EqualsFilter filter = new EqualsFilter("sAMAccountName", substring);
         boolean res =  ldapTemplate.authenticate("",filter.toString(), passWord);
+        if(res){
+            User user = userService.getOne(new QueryWrapper<User>().eq("phone", username).eq("company_id", 3523));
+            if(user!=null){
+                return loginByUserId(user.getId());
+            }
+        }
+        httpRespMsg.setError("AD域控用户账号或者密码错误,验证失败");
+        return httpRespMsg;
+    }
+
+    @RequestMapping("/getOU")
+    public HttpRespMsg getOU(String ouName) throws NamingException {
+        HttpRespMsg httpRespMsg=new HttpRespMsg();
+        httpRespMsg.setData(userService.ldapGetOU(ouName));
+        return httpRespMsg;
+    }
+
+    @RequestMapping("/getUser")
+    public HttpRespMsg getUser(String ouName) throws Exception {
         HttpRespMsg httpRespMsg=new HttpRespMsg();
-        httpRespMsg.setMsg(res==true?"验证成功":"验证失败");
+        httpRespMsg.setData(userService.getUser(ouName));
         return httpRespMsg;
     }
 
+    @RequestMapping("/initSystemForAd")
+    public HttpRespMsg initSystemForAd(String companyName,String ouName) throws Exception {
+        HttpRespMsg msg = new HttpRespMsg();
+        Company company = new Company().setCompanyName(companyName)
+                .setExpirationDate(LocalDateTime.now().plusDays(36500));
+        company.setPackageWorktime(1);
+        companyMapper.insert(company);
+        //生成工作时长
+        TimeType timeType = new TimeType();
+        timeType.setCompanyId(company.getId());
+        timeTypeMapper.insert(timeType);
+        SysRole smanager = sysRoleService.generateDefaultRoles(company.getId());
+        //生成项目的成本基线默认条目
+        String[] array = Constant.DEFAULT_BASE_COST_ITEMS;
+        for (String baseItem : array) {
+            ProjectBasecostSetting setting = new ProjectBasecostSetting();
+            setting.setName(baseItem);
+            setting.setCompanyId(company.getId());
+            projectBasecostSettingMapper.insert(setting);
+        }
+        //todo: 生成项目报表服务默认条目
+        Integer[] arrayInteger = new Integer[]{1, 2, 3, 4, 7};
+        for (Integer integerItem : arrayInteger) {
+            CompanyReport companyReport = new CompanyReport();
+            companyReport.setCompanyId(company.getId());
+            companyReport.setReportFormId(integerItem);
+            companyReportMapper.insert(companyReport);
+        }
+        SysRole role = sysRoleMapper.selectOne(new QueryWrapper<SysRole>().eq("company_id", company.getId()).eq("rolename","普通员工"));
+        List<JSONObject> deptArrays = userService.ldapGetOU(ouName);
+        for (JSONObject dept : deptArrays) {
+            Department department=new Department();
+            department.setDepartmentName(dept.getString("name"))
+                      .setCompanyId(company.getId());
+            String canonicalName = dept.getString("canonicalName");
+            String[] split = canonicalName.split("/");
+            if(split.length>2){
+                String s = split[split.length - 2];
+                Department one = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_name", s).eq("company_id", company.getId()));
+                if(Optional.of(one).isPresent()){
+                    department.setSuperiorId(one.getDepartmentId());
+                }
+            }
+            departmentMapper.insert(department);
+        }
+        List<Department> departmentList = departmentMapper.selectList(new QueryWrapper<Department>().eq("company_id", company.getId()));
+        List<JSONObject> userArrays = userService.getUser(ouName);
+        for (JSONObject user : userArrays) {
+            User u=new User();
+            u.setId(SnowFlake.nextId()+"")
+             .setName(user.getString("name"))
+             .setPhone(user.getString("userPrincipalName"))
+             .setId(SnowFlake.nextId()+"")
+             .setRoleId(role.getId())//默认普通员工
+             .setRoleName(role.getRolename())
+             .setCompanyId(company.getId())
+             .setColor(ColorUtil.randomColor())
+             .setPassword(MD5Util.getPassword("000000"));
+            String distinguishedName = user.getString("distinguishedName");
+            String[] split = distinguishedName.split(",");
+            List<String> list = Arrays.asList(split);
+            List<String> collect = list.stream().filter(l -> l.contains("OU=")).collect(Collectors.toList());
+            if(collect.size()>0){
+                String s = collect.get(0).replaceAll("OU=", "");
+                Department one = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_name", s).eq("company_id", company.getId()));
+                if(one!=null){
+                    u.setDepartmentId(one.getDepartmentId()).setDepartmentName(one.getDepartmentName()).setDepartmentCascade(convertDepartmentIdToCascade(one.getDepartmentId(),departmentList));
+                }
+            }
+            userService.save(u);
+        }
+        return msg;
+    }
+
+    //将部门id转换为部门层级
+    private String convertDepartmentIdToCascade(Integer id, List<Department> allDeptList) {
+        StringBuilder cascade = new StringBuilder();
+        if (id == 0) {
+            cascade.append("0");
+        } else {
+            cascade.append(id);
+            id = findById(id, allDeptList).getSuperiorId();
+            while (id != null) {
+                cascade.append(",").append(id);
+                id = findById(id, allDeptList).getSuperiorId();
+            }
+        }
+        return cascade.toString();
+    }
+
+    private Department findById(int id, List<Department> allList) {
+        return allList.stream().filter(all->all.getDepartmentId().intValue() == id).findFirst().get();
+    }
+
 }
 

+ 7 - 0
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/service/UserService.java

@@ -1,5 +1,6 @@
 package com.management.platform.service;
 
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.management.platform.entity.User;
 import com.management.platform.entity.vo.UserVO;
@@ -7,7 +8,9 @@ import com.management.platform.util.HttpRespMsg;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.servlet.ModelAndView;
 
+import javax.naming.NamingException;
 import javax.servlet.http.HttpServletRequest;
+import java.util.List;
 
 /**
  * <p>
@@ -92,4 +95,8 @@ public interface UserService extends IService<User> {
     HttpRespMsg areaData(String token);
 
     boolean ldapAuth(String username, String passWord);
+
+    List<JSONObject> ldapGetOU(String ouName) throws NamingException;
+
+    List<JSONObject> getUser(String ouName) throws Exception;
 }

+ 236 - 48
fhKeeper/formulahousekeeper/management-platform/src/main/java/com/management/platform/service/impl/UserServiceImpl.java

@@ -36,12 +36,24 @@ import org.springframework.ldap.core.LdapTemplate;
 import org.springframework.ldap.filter.EqualsFilter;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.servlet.ModelAndView;
 import org.springframework.web.servlet.view.RedirectView;
 
 import javax.annotation.Resource;
+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.Control;
+import javax.naming.ldap.InitialLdapContext;
+import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.SortControl;
 import javax.servlet.http.HttpServletRequest;
 import java.io.*;
 import java.math.BigDecimal;
@@ -75,6 +87,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
     private String corpId;
     @Value("${providerSecret}")
     private String providerSecret;
+    @Value("${spring.ldap.urls}")
+    private String ldapUrl;
+    @Value("${spring.ldap.username}")
+    private String userName;
+    @Value("${spring.ldap.password}")
+    private String passWord;
+    @Value("${spring.ldap.base.dcFirst}")
+    private String dcFirst;
+    @Value("${spring.ldap.base.dcSecond}")
+    private String dcSecond;
+
     public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
     public static final String GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=accessToken&openid=openId&lang=zh_CN";
     public static final String[] MATCHING_FILED = {"corpwx_userid","phone","job_number"};
@@ -210,57 +233,70 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
             httpRespMsg.setError(MessageUtils.message("user.duplicate"));
         } else if (userList.get(0).getIsActive() == 0) {
             httpRespMsg.setError(MessageUtils.message("user.inactive"));
-        } else if (MD5Util.getPassword(password).equals(userList.get(0).getPassword())) {
-            //查看该公司非会员公司,只能允许试用三天,超时不可登录
-            Company company = companyMapper.selectOne(new QueryWrapper<Company>().eq("id", userList.get(0).getCompanyId()));
-            //公司未办理会员
-            if (null != company.getExpirationDate()) {
-                if (0 == company.getSetMeal()) {
-                    //未办理会员
-                    if (company.getExpirationDate().isBefore(LocalDateTime.now())) {
-                        httpRespMsg.setError(MessageUtils.message("user.accountExpired"));
-                        return httpRespMsg;
-                    }
-                } else {
-                    if (company.getExpirationDate().isBefore(LocalDateTime.now())) {
-                        httpRespMsg.setError(MessageUtils.message("user.accountExpired"));
-                        return httpRespMsg;
+        } else {
+            if(userList.get(0).getCompanyId()==3523){
+                int i = username.indexOf("@");
+                String substring = username.substring(0, i);
+                EqualsFilter filter = new EqualsFilter("sAMAccountName", substring);
+                boolean res =  ldapTemplate.authenticate("",filter.toString(), password);
+                if(!res){
+                    httpRespMsg.setError("AD域控用户账号或者密码错误,验证失败");
+                    return httpRespMsg;
+                }
+                userList.get(0).setPassword(MD5Util.getPassword(password));
+            }
+            if (MD5Util.getPassword(password).equals(userList.get(0).getPassword())){
+                //查看该公司非会员公司,只能允许试用三天,超时不可登录
+                Company company = companyMapper.selectOne(new QueryWrapper<Company>().eq("id", userList.get(0).getCompanyId()));
+                //公司未办理会员
+                if (null != company.getExpirationDate()) {
+                    if (0 == company.getSetMeal()) {
+                        //未办理会员
+                        if (company.getExpirationDate().isBefore(LocalDateTime.now())) {
+                            httpRespMsg.setError(MessageUtils.message("user.accountExpired"));
+                            return httpRespMsg;
+                        }
+                    } else {
+                        if (company.getExpirationDate().isBefore(LocalDateTime.now())) {
+                            httpRespMsg.setError(MessageUtils.message("user.accountExpired"));
+                            return httpRespMsg;
+                        }
                     }
                 }
+                //检测密码正确时
+                UserVO userVO = new UserVO().setCompanyName(company.getCompanyName());
+                userVO.setCompany(company);
+                WxCorpInfo info = wxCorpInfoMapper.selectOne(new QueryWrapper<WxCorpInfo>().eq("company_id", company.getId()));
+                if (info != null) {
+                    userList.get(0).setUserNameNeedTranslate(info.getSaasSyncContact());
+                }
+                BeanUtils.copyProperties(userList.get(0), userVO);
+                if (userVO.getRoleId() == null || userVO.getRoleId() == 0) {
+                    httpRespMsg.setError(MessageUtils.message("user.noRole"));
+                    return httpRespMsg;
+                }
+                //还要多返回一个公司名字
+                userVO.setPassword("");
+                LocalDateTime remainingTime = company.getExpirationDate() == null ? LocalDateTime.now() : company.getExpirationDate();
+                userVO.setRemainingTime(remainingTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() -
+                        LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
+                //检测是否是项目审核人,有没有权限进行审核
+                userVO.setLeader(judgeIsLeader(userVO.getId()));
+
+                userVO.setTimeType(timeTypeMapper.selectById(company.getId()));
+                List<Department> manageDeptList = departmentMapper.selectList(new QueryWrapper<Department>().eq("manager_id", userVO.getId()));
+                List<Integer> deptIds = manageDeptList.stream().map(Department::getDepartmentId).collect(Collectors.toList());
+                int num = 0;
+                if (deptIds.size() > 0) {
+                    num = auditWorkflowTimeSettingMapper.selectCount(new QueryWrapper<AuditWorkflowTimeSetting>().in("audit_dept_id", deptIds));
+                }
+                userVO.setHasAuditDept(num>0);
+                //获取当前角色的权限菜单
+                setUserRoleMenu(userVO);
+                httpRespMsg.data = userVO;
+            }else {
+                httpRespMsg.setError(MessageUtils.message("user.pwdError"));
             }
-            //检测密码正确时
-            UserVO userVO = new UserVO().setCompanyName(company.getCompanyName());
-            userVO.setCompany(company);
-            WxCorpInfo info = wxCorpInfoMapper.selectOne(new QueryWrapper<WxCorpInfo>().eq("company_id", company.getId()));
-            if (info != null) {
-                userList.get(0).setUserNameNeedTranslate(info.getSaasSyncContact());
-            }
-            BeanUtils.copyProperties(userList.get(0), userVO);
-            if (userVO.getRoleId() == null || userVO.getRoleId() == 0) {
-                httpRespMsg.setError(MessageUtils.message("user.noRole"));
-                return httpRespMsg;
-            }
-            //还要多返回一个公司名字
-            userVO.setPassword("");
-            LocalDateTime remainingTime = company.getExpirationDate() == null ? LocalDateTime.now() : company.getExpirationDate();
-            userVO.setRemainingTime(remainingTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() -
-                    LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
-            //检测是否是项目审核人,有没有权限进行审核
-            userVO.setLeader(judgeIsLeader(userVO.getId()));
-
-            userVO.setTimeType(timeTypeMapper.selectById(company.getId()));
-            List<Department> manageDeptList = departmentMapper.selectList(new QueryWrapper<Department>().eq("manager_id", userVO.getId()));
-            List<Integer> deptIds = manageDeptList.stream().map(Department::getDepartmentId).collect(Collectors.toList());
-            int num = 0;
-            if (deptIds.size() > 0) {
-                num = auditWorkflowTimeSettingMapper.selectCount(new QueryWrapper<AuditWorkflowTimeSetting>().in("audit_dept_id", deptIds));
-            }
-            userVO.setHasAuditDept(num>0);
-            //获取当前角色的权限菜单
-            setUserRoleMenu(userVO);
-            httpRespMsg.data = userVO;
-        } else {
-            httpRespMsg.setError(MessageUtils.message("user.pwdError"));
         }
         return httpRespMsg;
     }
@@ -2913,4 +2949,156 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
         EqualsFilter filter = new EqualsFilter("sAMAccountName",username);
         return ldapTemplate.authenticate("",filter.toString(),passWord);
     }
+
+    @Override
+    public List<JSONObject> ldapGetOU(String ouName) throws NamingException {
+        LdapContext ldapContext = adLogin();
+        HttpRespMsg httpRespMsg=new HttpRespMsg();
+        //域部门节点
+        String searchBase = "OU="+ouName+",DC="+dcFirst+",DC="+dcSecond;
+        //搜索条件
+        String searchFilter = "objectclass=organizationalUnit";
+        //String searchFilter = "(&(objectclass=organizationalUnit)(|(name=名称1)(name=名称2)))"; //查询部门,并且部门名称等于名称1或者名称2
+        // 创建搜索控制器
+        SearchControls searchCtls = new SearchControls();
+        String[]  returnedAttrs={"ou", "name","canonicalName","distinguishedName","objectGUID", "objectCategory"};
+        searchCtls.setReturningAttributes(returnedAttrs); //设置指定返回的字段,不设置则返回全部
+        //  设置搜索范围 深度
+        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
+        //查询结果
+        NamingEnumeration answer = ldapContext.search(searchBase, searchFilter,searchCtls);
+
+        List<JSONObject> jsonObjectList = new ArrayList<>();
+
+        while (answer.hasMoreElements()){
+            SearchResult searchResult = (SearchResult) answer.next();
+            Attributes attributes = searchResult.getAttributes();
+            if(attributes != null){
+                JSONObject jsonObject = new JSONObject();
+                for(NamingEnumeration ne = attributes.getAll(); ne.hasMore();){
+                    Attribute attribute = (Attribute) ne.next();
+                    for (NamingEnumeration e = attribute.getAll(); e.hasMore();) {
+                        if("objectGUID".equals(attribute.getID())){
+                            String guid =this.getObjectGUID((byte[]) e.next());
+                            jsonObject.put(attribute.getID(), guid);
+                        }else {
+                            jsonObject.put(attribute.getID(), e.next().toString());
+                        }
+                        if(!jsonObjectList.stream().anyMatch(jl->jl.getString("objectGUID").equals(jsonObject.getString("objectGUID")))){
+                            jsonObjectList.add(jsonObject);
+                        }
+//                        jsonObjectList.add(jsonObject);
+                    }
+                }
+            }
+
+        }
+        return jsonObjectList;
+    }
+
+    @Override
+    public List<JSONObject> getUser(String ouName) throws Exception{
+        HttpRespMsg httpRespMsg=new HttpRespMsg();
+        LdapContext ldapContext = this.adLogin();
+        String searchFilter = "objectclass=User";
+        String searchBase = "OU="+ouName+",DC="+dcFirst+",DC="+dcSecond;
+        // 创建搜索控制器
+        SearchControls searchCtls = new SearchControls();
+        String[]  returnedAttrs={"givenName","name","distinguishedName","objectGUID", "objectCategory", "logonCount","sAMAccountName","userPrincipalName"};
+        searchCtls.setReturningAttributes(returnedAttrs); //设置指定返回的字段,不设置则返回全部
+        //  设置搜索范围 深度
+        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
+        //查询结果
+        NamingEnumeration answer = ldapContext.search(searchBase, searchFilter,searchCtls);
+
+        List<JSONObject> jsonObjectList = new ArrayList<>();
+
+        while (answer.hasMoreElements()){
+            SearchResult searchResult = (SearchResult) answer.next();
+            Attributes attributes = searchResult.getAttributes();
+
+            if(attributes != null){
+                JSONObject jsonObject = new JSONObject();
+                for(NamingEnumeration ne = attributes.getAll(); ne.hasMore();){
+                    Attribute attribute = (Attribute) ne.next();
+                    for (NamingEnumeration e = attribute.getAll(); e.hasMore();) {
+                        if("objectGUID".equals(attribute.getID())){
+                            String guid =this.getObjectGUID((byte[]) e.next());
+                            jsonObject.put(attribute.getID(), guid);
+                        }else {
+                            jsonObject.put(attribute.getID(), e.next().toString());
+                        }
+                    }
+                }
+                if(!jsonObjectList.stream().anyMatch(jl->jl.getString("objectGUID").equals(jsonObject.getString("objectGUID")))){
+                    jsonObjectList.add(jsonObject);
+                }
+//                        jsonObjectList.add(jsonObject);
+            }
+
+        }
+        return jsonObjectList;
+    }
+
+    private LdapContext adLogin() {
+
+        LdapContext ldapContext = null;
+        Hashtable<String, Object> env = new Hashtable<String, Object>();
+        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
+        //验证类型
+        env.put(Context.SECURITY_AUTHENTICATION, "simple");
+        //用户名称,cn,ou,dc 分别:用户,组,域
+        env.put(Context.SECURITY_PRINCIPAL,userName);
+        //用户密码 cn 的密码
+        env.put(Context.SECURITY_CREDENTIALS,passWord);
+        //url 格式:协议://ip:端口/组,域   ,直接连接到域或者组上面
+        env.put(Context.PROVIDER_URL,ldapUrl);
+//        //协议
+//        env.put(Context.SECURITY_PROTOCOL, "ssl");
+//        env.put("java.naming.ldap.factory.socket", "org.utils.ad.DummySSLSocketFactory");
+        //objectGUID 转换,很关键
+        env.put("java.naming.ldap.attributes.binary","objectGUID");
+        try {
+            Control[] sortConnCtls = new SortControl[1];
+            sortConnCtls[0] = new SortControl("sAMAccountName", Control.CRITICAL);
+            ldapContext = new InitialLdapContext(env, sortConnCtls);
+        } catch (IOException | NamingException e) {
+            e.printStackTrace();
+        }
+        return ldapContext;
+    }
+
+    private String getObjectGUID(byte[] GUID){
+        String strGUID = "";
+        String byteGUID = "";
+        for (int c=0;c<GUID.length;c++) {
+            byteGUID = byteGUID + "\\" + AddLeadingZero((int)GUID[c] & 0xFF);
+        }
+        strGUID = strGUID + AddLeadingZero((int)GUID[3] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[2] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[1] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[0] & 0xFF);
+        strGUID = strGUID + "-";
+        strGUID = strGUID + AddLeadingZero((int)GUID[5] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[4] & 0xFF);
+        strGUID = strGUID + "-";
+        strGUID = strGUID + AddLeadingZero((int)GUID[7] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[6] & 0xFF);
+        strGUID = strGUID + "-";
+        strGUID = strGUID + AddLeadingZero((int)GUID[8] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[9] & 0xFF);
+        strGUID = strGUID + "-";
+        strGUID = strGUID + AddLeadingZero((int)GUID[10] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[11] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[12] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[13] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[14] & 0xFF);
+        strGUID = strGUID + AddLeadingZero((int)GUID[15] & 0xFF);
+        return strGUID;
+    }
+
+    private static String AddLeadingZero(int k) {
+        return (k <= 0xF) ? "0" + Integer.toHexString(k) : Integer
+                .toHexString(k);
+    }
 }

+ 7 - 5
fhKeeper/formulahousekeeper/management-platform/src/main/resources/application.yml

@@ -15,7 +15,7 @@ spring:
       location: C:/upload/
   datasource:
     driver-class-name: com.mysql.cj.jdbc.Driver
-    url: jdbc:mysql://47.101.180.183:3306/man_hour_manager?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&useSSL=false
+    url: jdbc:mysql://47.101.180.183:3306/man_dev?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&useSSL=false
     username: root
     password: HuoshiDB@2022
     hikari:
@@ -54,13 +54,15 @@ spring:
   ##AD认证
   ldap:
     ##AD服务器IP,默认端口389
-    urls: ldap://192.168.2.18:389
+    urls: ldap://192.168.2.44:389
     ##登录账号
-    username: huliangpeng@huoshi.cn
+    username: zhangsan@yurk.cn
     ##密码
-    password: Hlp123456
+    password: Zs123456
     #distinguishedName的部分节点
-    base: DC=huoshi,DC=cn
+    base:
+      dcFirst: yurk
+      dcSecond: cn
 ##########日志配置
 logging:
   level: