[0002]域控AD打通与SAP HCM系统集成,实现组织、人员实时同步并企业内部统一认证管控

    为了更好的实现企业统一安全管控,需要对深信服上网、云桌面、邮箱、VPN等系统进行域控统一账号和安全管理,以下是大致的实现方案。

一、根据前期调研进行集成IT方案设计并高层汇报,见图:

 

二、SAP PO接口字段对照详细IT方案设计

三、代码实现(因每个企业对应的系统不同,此处仅附核心代码参考)

  1         #region GetDirectoryObject
  2 
  3 
  4         /// <summary>
  5         /// 获得DirectoryEntry对象实例,以管理员登陆AD
  6         /// </summary>
  7         /// <returns></returns>
  8         private static DirectoryEntry GetDirectoryObject()
  9         {
 10             DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
 11             return entry;
 12         }
 13 
 14         /// <summary>
 15         /// /根据指定用户名和密码获得相应DirectoryEntry实体
 16         /// </summary>
 17         /// <param name="userName"></param>
 18         /// <param name="password"></param>
 19         /// <returns></returns>
 20         private static DirectoryEntry GetDirectoryObject(string userName, string password)
 21         {
 22             DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);
 23             return entry;
 24         }
 25 
 26         /// <summary>
 27         ///  i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com
 28         /// </summary>
 29         /// <param name="domainReference"></param>
 30         /// <returns></returns>
 31         private static DirectoryEntry GetDirectoryObject(string domainReference)
 32         {
 33             DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);
 34             return entry;
 35         }
 36 
 37         /// <summary>
 38         /// 获得以UserName,Password创建的DirectoryEntry
 39         /// </summary>
 40         /// <param name="domainReference"></param>
 41         /// <param name="userName"></param>
 42         /// <param name="password"></param>
 43         /// <returns></returns>
 44         private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
 45         {
 46             DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
 47             return entry;
 48         }
 49 
 50         /// <summary>
 51         /// 通过objectGUID获取DirectoryEntry对象
 52         /// </summary>
 53         /// <param name="strParamGUID">要查找的对象序列号。</param>
 54         /// <returns>Ou对象</returns>
 55         public static DirectoryEntry GetDirectoryObjectByGUID(string strParamGUID)
 56         {
 57             try
 58             {
 59                 string objectGUID = Guid2OctetString(new Guid(strParamGUID));//转换GUID
 60                 DirectoryEntry de = GetDirectoryObject();
 61                 DirectorySearcher deSearch = new DirectorySearcher();//查询
 62                 deSearch.SearchRoot = de;
 63                 deSearch.Filter = "(&(objectGUID=" + objectGUID + "))";
 64                 deSearch.SearchScope = SearchScope.Subtree;
 65                 SearchResult results = deSearch.FindOne();
 66                 if (results != null)
 67                 {
 68                     return new DirectoryEntry(results.Path, ADUser, ADPassword, AuthenticationTypes.Secure);
 69                 }
 70                 else
 71                 {
 72                     return null;
 73                 }
 74             }
 75             catch
 76             {
 77                 return null;
 78             }
 79         }
 80         /// <summary>
 81         /// 通过objectGUID获取DirectoryEntry对象
 82         /// </summary>
 83         /// <param name="deRoot"></param>
 84         /// <param name="objectGUID"></param>
 85         /// <returns></returns>
 86         private DirectoryEntry GetDirectoryObjectByGUID(DirectoryEntry deRoot, Guid objectGUID)
 87         {
 88             string queryGuid = Guid2OctetString(objectGUID);
 89             DirectorySearcher searcher = new DirectorySearcher(deRoot, "(objectGUID=" + queryGuid + ")");
 90             SearchResult sr = searcher.FindOne();
 91             if (sr == null) return null;
 92             return sr.GetDirectoryEntry();
 93         }
 94 
 95         /// <summary>
 96         /// 将GUID转换为16进制字符串
 97         /// </summary>
 98         /// <param name="objectGuid"></param>
 99         /// <returns></returns>
100         private static string Guid2OctetString(Guid objectGuid)
101         {
102             byte[] byteGuid = objectGuid.ToByteArray();
103             StringBuilder sb = new StringBuilder();
104             foreach (byte b in byteGuid)
105             {
106                 sb.Append(@"\" + b.ToString("x2"));
107             }
108             return sb.ToString();
109         }
110 
111         #endregion
112 
113         #region 对Ou操作
114         /// <summary>
115         /// Enumerate Objects in an OU
116         /// The parameter OuDn is the Organizational Unit distinguishedName such as OU=Users,dc=myDomain,dc=com
117         /// </summary>
118         /// <param name="OuDn"></param>
119         /// <returns></returns>
120         public static ArrayList EnumerateOU(string OuDn)
121         {
122             ArrayList alObjects = new ArrayList();
123             try
124             {
125                 DirectoryEntry directoryObject = GetDirectoryObject();
126                 foreach (DirectoryEntry child in directoryObject.Children)
127                 {
128                     string childPath = child.Path.ToString();
129                     alObjects.Add(childPath.Remove(0, 7));
130                     //remove the LDAP prefix from the path
131 
132                     child.Close();
133                     child.Dispose();
134                 }
135                 directoryObject.Close();
136                 directoryObject.Dispose();
137             }
138             catch (DirectoryServicesCOMException e)
139             {
140                 Console.WriteLine("An Error Occurred: " + e.Message.ToString());
141             }
142             return alObjects;
143         }
144        
145 
146         /// <summary>
147         /// 使用OU的部分路径在Active Directory中搜索OU,传入参数为OU名称。
148         /// </summary>
149         /// <param name="deBase"></param>
150         /// <param name="ou1"></param>
151         /// <param name="ou2"></param>
152         /// <returns></returns>
153         public static List<DirectoryEntry> OuInTheFormOf(DirectoryEntry deBase, string strou1, string strou2)
154         {
155             List<DirectoryEntry> deList = null;
156             /* Directory Search
157                    */
158             DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
159             dsLookFor.Filter = strou1;
160             dsLookFor.SearchScope = SearchScope.Subtree;
161             dsLookFor.PropertiesToLoad.Add("ou");
162             SearchResultCollection srcOUs = dsLookFor.FindAll();
163             if (srcOUs.Count != 0)
164             {
165                 deList = new List<DirectoryEntry>();
166                 foreach (SearchResult srOU in srcOUs)
167                 {
168                     DirectoryEntry deOU = srOU.GetDirectoryEntry();
169                     if (deOU.Parent.Name.ToUpper() == strou2.ToUpper())
170                         deList.Add(deOU);
171                 }
172             }
173             return deList;
174             ////下面是用法。
175             //    
176             //    DirectoryEntry deBase = new DirectoryEntry("LDAP://WM2008R2ENT:389/dc=dom,dc=fr");
177             //    List<DirectoryEntry> l = OuInTheFormOf(deBase, "ou=Clerks", "ou=OfficeA");
178             //    foreach (DirectoryEntry deTmp in l)
179             //    {
180             //        Console.WriteLine(deTmp.Properties["distinguishedName"].Value);
181             //    }
182         }
183 
184         /// <summary>
185         ///  创建Ou单位,传入父组织参数为Ou组织名称。
186         /// </summary>
187         /// <param name="strParentOu">父部门名称 </param>
188         /// <param name="strChilderOu">子部门名称</param>
189         /// <param name="strinGuid">返回的UUID值。</param>
190         /// <returns></returns>
191         public DirectoryEntry GreateOU(string strParentOU, string strChilderOU,ref string strinGuid)
192         {
193             DirectoryEntry entry = GetDirectoryObject(strParentOU);
194             DirectoryEntry OU = entry.Children.Add("OU=" + strChilderOU, "organizationalUnit");
195             OU.CommitChanges();
196             strinGuid = OU.Guid.ToString();
197             return OU;
198         }
199         /// <summary>
200         /// 创建最顶级的组织Ou,他是没有上级部门的。
201         /// </summary>
202         /// <param name="strChilderOU"></param>
203         /// <param name="strinGuid"></param>
204         /// <returns></returns>
205         public static DirectoryEntry GreateOU(string strChilderOU, ref string strinGuid)
206         {
207             DirectoryEntry entry = GetDirectoryObject();
208             DirectoryEntry OU = entry.Children.Add("OU=" + strChilderOU, "organizationalUnit");
209             OU.Properties["description"].Value = "正在生效";
210             OU.CommitChanges();
211             strinGuid = OU.Guid.ToString();
212             return OU;
213         }
214 
215 
216         /// <summary>
217         /// 创建Ou单位,传入父组织参数为Ou对象UUID。
218         /// </summary>
219         /// <param name="strParentOU"></param>
220         /// <param name="strChilderOU"></param>
221         /// <param name="strinGuid"></param>
222         /// <returns></returns>
223         public DirectoryEntry GreateOUByGUID(string strParentOUGuid, string strChilderOU, ref string strinGuid)
224         {
225             DirectoryEntry entry = GetDirectoryObjectByGUID(strParentOUGuid);
226             DirectoryEntry OU = entry.Children.Add("OU=" + strChilderOU, "organizationalUnit");
227             strinGuid = OU.Guid.ToString();
228             OU.CommitChanges();
229             return OU;
230         }
231 
232         /// <summary>
233         /// 删除Ou单位,在业务上使用时废弃了ou 他下面的用户全部禁用。
234         /// </summary>
235         /// <param name="strParentOU"></param>
236         /// <param name="strOUName"></param>
237         public static void DeleteOU(string strParentOU, string strOUName)
238         {
239             DirectoryEntry entry = GetDirectoryObject(strParentOU);
240             DirectoryEntry group = entry.Children.Find(strOUName);
241             if (group != null)
242                 entry.Children.Remove(group);
243         }
244         /// <summary>
245         /// 删除Ou单位,传入参数为GUID。
246         /// </summary>
247         /// <param name="strParamGUID"></param>
248         public static void DeleteOUByGUID(string strParamGUID)
249         {
250             DirectoryEntry entry = GetDirectoryObjectByGUID(strParamGUID);
251             if (entry != null)
252                 entry.Children.Remove(entry);
253         }
254 
255         /// <summary>
256         /// 修改Ou单位,传入参数为OU名称。
257         /// </summary>
258         /// <param name="strParentOU"></param>
259         /// <param name="strOUName"></param>
260         public static void ModifyOU(string strParentOU, string strOUName)
261         {
262             DirectoryEntry entry = GetDirectoryObject(strParentOU);
263             DirectoryEntry group = entry.Children.Find(strOUName);
264             if (group != null)
265             {
266                 //先放在这儿,有属性再说。
267                 group.Properties["description"].Value = "Change the description.";
268                 group.Rename("NewName");
269                 group.CommitChanges();
270             }
271         }
272         /// <summary>
273         /// 修改Ou单位,传入参数为OU名称。
274         /// </summary>
275         /// <param name="strParamGUID"></param>
276         public static  void ModifyOUByGUID(string strParamGUID,string strNewName,string strDescription)
277         {
278             try
279             {
280                 DirectoryEntry entry = GetDirectoryObjectByGUID(strParamGUID);
281                 if (entry != null)
282                 {
283                     //先放在这儿,有属性再说。
284                     entry.Properties["description"].Value = strDescription;
285                     //entry.Rename("OU=第二部门,OU=双胞胎集团顶级部门,DC=contoso,DC=com");
286                     //修改名称,必须为上面的方式进行拼装,新Ou名称。
287                     entry.Rename(strNewName);
288                     entry.CommitChanges();
289                 }
290             }
291             catch (Exception e)
292             {
293                 Apibase.WriteLog("时间:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",修改用户部门失败。" + "\r\n" + "原因:" + e.Message.ToString());
294             }
295         }
296 
297 
298         /// <summary>
299         /// 移动Ou单位,传入参数为Ou组织名称。
300         /// </summary>
301         /// <param name="strParentOUOld"></param>
302         /// <param name="strOUName"></param>
303         /// <param name="strParentOUNew"></param>
304         public static void MoveOU(string strParentOld, string strOUName,string strParentNew)
305         {
306             DirectoryEntry entry1 = GetDirectoryObject(strParentOld);
307             DirectoryEntry entry2 = GetDirectoryObject(strParentNew);
308             DirectoryEntry group = entry1.Children.Find(strOUName);
309             if (group != null)
310             {
311                 group.MoveTo(entry2);
312             }
313         }
314         /// <summary>
315         /// 移动Ou单位,传入参数为Ou组织GUID。
316         /// </summary>
317         /// <param name="strParamGUID"></param>
318         /// <param name="strParentNew"></param>
319         public static void MoveOUByGUID(string strParamGUID, string strParentNew)
320         {
321             DirectoryEntry entry2 = GetDirectoryObjectByGUID(strParentNew);
322             DirectoryEntry group = GetDirectoryObjectByGUID(strParamGUID);
323             if (entry2!=null && group != null)
324             {
325                 if (strParentNew != group.Parent.Guid.ToString())
326                 { 
327                     group.MoveTo(entry2);
328                 }
329             }
330         }
331 
332 
333         #endregion
334 
335         #region GetDirectoryEntry
336 
337         ///
338         /// 根据用户公共名称取得用户的 对象
339         ///
340         /// 用户公共名称
341         /// 如果找到该用户,则返回用户的 对象;否则返回 null
342         public static DirectoryEntry GetDirectoryEntry(string commonName)
343         {
344             DirectoryEntry de = GetDirectoryObject();
345             DirectorySearcher deSearch = new DirectorySearcher(de);
346             deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
347             deSearch.SearchScope = SearchScope.Subtree;
348 
349             try
350             {
351                 SearchResult result = deSearch.FindOne();
352                 de = new DirectoryEntry(result.Path);
353                 return de;
354             }
355             catch
356             {
357                 return null;
358             }
359         }
360 
361         ///
362         /// 根据用户公共名称和密码取得用户的 对象。
363         ///
364         /// 用户公共名称
365         /// 用户密码
366         /// 如果找到该用户,则返回用户的 对象;否则返回 null
367         public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
368         {
369             DirectoryEntry de = GetDirectoryObject(commonName, password);
370             DirectorySearcher deSearch = new DirectorySearcher(de);
371             deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
372             deSearch.SearchScope = SearchScope.Subtree;
373 
374             try
375             {
376                 SearchResult result = deSearch.FindOne();
377                 de = new DirectoryEntry(result.Path);
378                 return de;
379             }
380             catch
381             {
382                 return null;
383             }
384         }
385 
386         ///
387         /// 根据用户帐号称取得用户的 对象
388         ///
389         /// 用户帐号名
390         /// 如果找到该用户,则返回用户的 对象;否则返回 null
391         public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
392         {
393             DirectoryEntry de = GetDirectoryObject();
394             DirectorySearcher deSearch = new DirectorySearcher(de);
395             deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
396             deSearch.SearchScope = SearchScope.Subtree;
397 
398             try
399             {
400                 SearchResult result = deSearch.FindOne();
401                 de = new DirectoryEntry(result.Path);
402                 return de;
403             }
404             catch
405             {
406                 return null;
407             }
408         }
409 
410         ///
411         /// 根据用户帐号和密码取得用户的 对象
412         ///
413         /// 用户帐号名
414         /// 用户密码
415         /// 如果找到该用户,则返回用户的 对象;否则返回 null
416         public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
417         {
418             DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
419             if (de != null)
420             {
421                 string commonName = de.Properties["cn"][0].ToString();
422 
423                 if (GetDirectoryEntry(commonName, password) != null)
424                     return GetDirectoryEntry(commonName, password);
425                 else
426                     return null;
427             }
428             else
429             {
430                 return null;
431             }
432         }
433 
434         ///
435         /// 根据组名取得用户组的 对象
436         ///
437         /// 组名
438         ///
439         public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
440         {
441             DirectoryEntry de = GetDirectoryObject();
442             DirectorySearcher deSearch = new DirectorySearcher(de);
443             deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
444             deSearch.SearchScope = SearchScope.Subtree;
445 
446             try
447             {
448                 SearchResult result = deSearch.FindOne();
449                 de = new DirectoryEntry(result.Path);
450                 return de;
451             }
452             catch
453             {
454                 return null;
455             }
456         }
457         /// <summary>
458         /// 根据Ou的GUID来获得下该组织下全部用户。
459         /// </summary>
460         /// <param name="groupGUID"></param>
461         /// <returns></returns>
462         public static ArrayList GetListOfAdUsersByGroupByGUID(string groupGUID)
463         {
464             ArrayList aryReturn = new ArrayList();
465             DirectoryEntry entry = GetDirectoryObjectByGUID(groupGUID);
466             if (entry != null)
467             {
468                 System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
469                 mySearcher.Filter = ("(objectClass=user)"); //user表示用户
470                 foreach (System.DirectoryServices.SearchResult result in mySearcher.FindAll())
471                 {
472                     aryReturn.Add(result.Properties["name"][0].ToString());
473                 }
474             }
475             return aryReturn;
476         }
477 
478         #endregion
479 
480         #region GetProperty
481 
482         ///
483         /// 获得指定 指定属性名对应的值
484         ///
485         ///
486         /// 属性名称
487         /// 属性值
488         public static string GetProperty(DirectoryEntry de, string propertyName)
489         {
490             if (de.Properties.Contains(propertyName))
491             {
492                 return de.Properties[propertyName][0].ToString();
493             }
494             else
495             {
496                 return string.Empty;
497             }
498         }
499 
500         ///
501         /// 获得指定搜索结果 中指定属性名对应的值
502         ///
503         ///
504         /// 属性名称
505         /// 属性值
506         public static string GetProperty(SearchResult searchResult, string propertyName)
507         {
508             if (searchResult.Properties.Contains(propertyName))
509             {
510                 return searchResult.Properties[propertyName][0].ToString();
511             }
512             else
513             {
514                 return string.Empty;
515             }
516         }
517 
518  
519 
520         ///
521         /// 设置指定 的属性值
522         ///
523         ///
524         /// 属性名称
525         /// 属性值
526         public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
527         {
528             if (propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
529             {
530                 if (de.Properties.Contains(propertyName))
531                 {
532                     de.Properties[propertyName][0] = propertyValue;
533                 }
534                 else
535                 {
536                     de.Properties[propertyName].Add(propertyValue);
537                 }
538             }
539         }
540 
541         #endregion
542 
543         #region 对用户操作
544         ///
545         /// 创建新的用户
546         ///
547         /// DN 位置。例如:OU=共享平台 或 CN=Users
548         /// 公共名称
549         /// 帐号
550         /// 密码
551         ///
552         public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
553         {
554             DirectoryEntry entry = GetDirectoryObject();
555             DirectoryEntry subEntry = entry.Children.Find(ldapDN);
556             DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
557             deUser.Properties["sAMAccountName"].Value = sAMAccountName;
558             deUser.CommitChanges();
559             ADHelper.EnableUser(commonName);
560             ADHelper.SetPassword(commonName, password);
561             deUser.Close();
562             return deUser;
563         }
564 
565        
566         ///
567         /// 创建新的用户。默认创建在 Users 单元下。
568         ///
569         /// 公共名称
570         /// 帐号
571         /// 密码
572         ///
573         public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)
574         {
575             return CreateNewUser("CN=Users", commonName, sAMAccountName, password);
576         }
577 
578         
579        
580         ///
581         /// 判断指定公共名称的用户是否存在
582         ///
583         /// 用户公共名称
584         /// 如果存在,返回 true;否则返回 false
585         public static bool IsUserExists(string commonName)
586         {
587             DirectoryEntry de = GetDirectoryObject();
588             DirectorySearcher deSearch = new DirectorySearcher(de);
589             deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";       // LDAP 查询串
590             SearchResultCollection results = deSearch.FindAll();
591 
592             if (results.Count == 0)
593                 return false;
594             else
595                 return true;
596         }
597 
598         ///
599         /// 判断用户帐号是否激活
600         ///
601         /// 用户帐号属性控制器
602         /// 如果用户帐号已经激活,返回 true;否则返回 false
603         public static bool IsAccountActive(int userAccountControl)
604         {
605             int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
606             int flagExists = userAccountControl & userAccountControl_Disabled;
607 
608             if (flagExists > 0)
609                 return false;
610             else
611                 return true;
612         }
613 
614         ///
615         /// 判断用户与密码是否足够以满足身份验证进而登录
616         ///
617         /// 用户公共名称
618         /// 密码
619         /// 如能可正常登录,则返回 true;否则返回 false
620         public static LoginResult Login(string commonName, string password)
621         {
622             DirectoryEntry de = GetDirectoryEntry(commonName);
623 
624             if (de != null)
625             {
626                 // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
627                 int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
628                 de.Close();
629 
630                 if (!IsAccountActive(userAccountControl))
631                     return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
632 
633                 if (GetDirectoryEntry(commonName, password) != null)
634                     return LoginResult.LOGIN_USER_OK;
635                 else
636                     return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
637             }
638             else
639             {
640                 return LoginResult.LOGIN_USER_DOESNT_EXIST;
641             }
642         }
643 
644         ///
645         /// 判断用户帐号与密码是否足够以满足身份验证进而登录
646         ///
647         /// 用户帐号
648         /// 密码
649         /// 如能可正常登录,则返回 true;否则返回 false
650         public static LoginResult LoginByAccount(string sAMAccountName, string password)
651         {
652             DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
653 
654             if (de != null)
655             {
656                 // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
657                 int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
658                 de.Close();
659 
660                 if (!IsAccountActive(userAccountControl))
661                     return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
662 
663                 if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
664                     return LoginResult.LOGIN_USER_OK;
665                 else
666                     return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
667             }
668             else
669             {
670                 return LoginResult.LOGIN_USER_DOESNT_EXIST;
671             }
672         }
673 
674         ///
675         /// 设置用户密码,管理员可以通过它来修改指定用户的密码。
676         ///
677         /// 用户公共名称
678         /// 用户新密码
679         public static void SetPassword(string strUserGUID, string newPassword)
680         {
681             DirectoryEntry de = GetDirectoryObjectByGUID(strUserGUID);
682 
683             // 模拟超级管理员,以达到有权限修改用户密码
684             impersonate.BeginImpersonate();
685             de.Invoke("SetPassword", new object[] { newPassword });
686             impersonate.StopImpersonate();
687 
688             de.Close();
689         }
690 
691         ///
692         /// 设置帐号密码,管理员可以通过它来修改指定帐号的密码。
693         ///
694         /// 用户帐号
695         /// 用户新密码
696         public static void SetPasswordByAccount(string sAMAccountName, string newPassword)
697         {
698             DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
699 
700             // 模拟超级管理员,以达到有权限修改用户密码
701             IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
702             impersonate.BeginImpersonate();
703             de.Invoke("SetPassword", new object[] { newPassword });
704             impersonate.StopImpersonate();
705 
706             de.Close();
707         }
708 
709         ///
710         /// 修改用户密码
711         ///
712         /// 用户公共名称
713         /// 旧密码
714         /// 新密码
715         public static void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
716         {
717             // to-do: 需要解决密码策略问题
718             DirectoryEntry oUser = GetDirectoryEntry(commonName);
719             oUser.Invoke("ChangePassword", new Object[] { oldPassword, newPassword });
720             oUser.Close();
721         }
722 
723         ///
724         /// 启用指定公共名称的用户
725         ///
726         /// 用户公共名称
727         public static void EnableUser(string strUserGUID)
728         {
729             EnableUser(GetDirectoryObjectByGUID(strUserGUID));
730         }
731 
732         ///
733         /// 启用指定 的用户
734         ///
735         ///
736         public static void EnableUser(DirectoryEntry de)
737         {
738             try
739             {
740                 impersonate.BeginImpersonate();
741                 de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
742                 de.CommitChanges();
743                 impersonate.StopImpersonate();
744                 de.Close();
745             }
746             catch (Exception e)
747             {
748                 Apibase.WriteLog("时间:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",写入AD用户对象失败。" + "\r\n" + "原因:" + e.Message.ToString());
749             }
750         }
751 
752         ///
753         /// 禁用指定公共名称的用户
754         ///
755         /// 用户公共名称
756         public static void DisableUser(string strUserGUID)
757         {
758             DisableUser(GetDirectoryObjectByGUID(strUserGUID));
759         }
760 
761         ///
762         /// 禁用指定 的用户
763         ///
764         ///
765         public static void DisableUser(DirectoryEntry de)
766         {
767             impersonate.BeginImpersonate();
768             de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
769             de.CommitChanges();
770             impersonate.StopImpersonate();
771             de.Close();
772         }
773 
774         ///
775         /// 将指定的用户添加到指定的组中。默认为 Users 下的组和用户。
776         ///
777         /// 用户公共名称
778         /// 组名
779         public static void AddUserToGroup(string userCommonName, string groupName)
780         {
781             DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
782             DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
783             if (oGroup != null && oUser != null)
784             {
785                 impersonate.BeginImpersonate();
786                 oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
787                 oGroup.CommitChanges();
788                 impersonate.StopImpersonate();
789 
790                 oGroup.Close();
791                 oUser.Close();
792             }
793         }
794 
795 
796         /// <summary>
797         /// 将指定的用户添加到指定的组中,参数为OU的GUID。
798         /// </summary>
799         /// <param name="userCommonName"></param>
800         /// <param name="strParamGUID"></param>
801         public static void AddUserToGroupByGUID(string userCommonName, string strParamGUID)
802         {
803             try
804             {
805                 DirectoryEntry oGroup = GetDirectoryObjectByGUID(strParamGUID);
806                 DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
807                 if (oGroup != null && oUser != null)
808                 {
809                     impersonate.BeginImpersonate();
810                     oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
811                     oGroup.CommitChanges();
812                     impersonate.StopImpersonate();
813                     oGroup.Close();
814                     oUser.Close();
815                 }
816             }
817             catch(Exception e)
818             {
819                 Apibase.WriteLog("时间:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",插入用户部门失败。" + "\r\n" + "原因:" + e.Message.ToString());
820             }
821 
822         }
823 
824         ///
825         /// 将用户从指定组中移除。默认为 Users 下的组和用户。
826         ///
827         /// 用户公共名称
828         /// 组名
829         public static void RemoveUserFromGroup(string userCommonName, string groupName)
830         {
831             DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
832             DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
833             if (oGroup != null && oUser != null)
834             {
835                 impersonate.BeginImpersonate();
836                 oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
837                 oGroup.CommitChanges();
838                 impersonate.StopImpersonate();
839 
840                 oGroup.Close();
841                 oUser.Close();
842             }
843         }
844 
845         public static void RemoveUserFromGroupByGUID(string userCommonName, string strParamGUID)
846         {
847             DirectoryEntry oGroup = GetDirectoryObjectByGUID(strParamGUID);
848             DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
849             if (oGroup != null && oUser != null)
850             {
851                 impersonate.BeginImpersonate();
852                 oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
853                 oGroup.CommitChanges();
854                 impersonate.StopImpersonate();
855 
856                 oGroup.Close();
857                 oUser.Close();
858             }
859         }
860         /// <summary>
861         /// 将用户移动至指定的Ou下。
862         /// </summary>
863         /// <param name="userCommonName"></param>
864         /// <param name="strParamGUID"></param>
865         public static void ExchangeUserToNewGroupByGUID(string strUserGUID, string strParamGUID)
866         {
867             try
868             {
869                 DirectoryEntry oGroup = GetDirectoryObjectByGUID(strParamGUID);
870                 DirectoryEntry oUser = GetDirectoryObjectByGUID(strUserGUID);
871                 if (oGroup != null && oUser != null)
872                 {
873                     //确认传入的父部门GUID,不等于 用户当前父Ou的GUID才进行移动。
874                     if (strParamGUID != oUser.Parent.Guid.ToString())
875                     {
876                         impersonate.BeginImpersonate();
877                         oUser.MoveTo(oGroup);
878                         oUser.CommitChanges();
879                         oGroup.CommitChanges();
880                         impersonate.StopImpersonate();
881                         oGroup.Close();
882                         oUser.Close();
883                     }
884                 }
885             }
886             catch (Exception e)
887             {
888                 Apibase.WriteLog("时间:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",移动用户部门失败。" + "\r\n" + "原因:" + e.Message.ToString());
889             }
890         }
891 
892 
893 
894 
895         #endregion
View Code

四、实现效果

posted @ 2020-09-25 15:17  花椒开发笔记  阅读(1259)  评论(0)    收藏  举报