C#操作域用户

  1 using System;
  2 using System.DirectoryServices;
  3 
  4 namespace SystemFrameworks.Helper
  5 {
  6      ///
  7      ///活动目录辅助类。封装一系列活动目录操作相关的方法。
  8      ///
  9      public sealed class ADHelper
 10      {
 11          ///
 12          ///域名
 13          ///
 14          private static string DomainName = "MyDomain";
 15          ///
 16          /// LDAP 地址
 17          ///
 18          private static string LDAPDomain = "DC=MyDomain,DC=local";
 19          ///
 20          /// LDAP绑定路径
 21          ///
 22          private static string ADPath = "LDAP://brooks.mydomain.local";
 23          ///
 24          ///登录帐号
 25          ///
 26          private static string ADUser = "Administrator";
 27          ///
 28          ///登录密码
 29          ///
 30          private static string ADPassword = "password";
 31          ///
 32          ///扮演类实例
 33          ///
 34          private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
 35 
 36          ///
 37          ///用户登录验证结果
 38          ///
 39          public enum LoginResult
 40          {
 41               ///
 42               ///正常登录
 43               ///
 44               LOGIN_USER_OK = 0,
 45               ///
 46               ///用户不存在
 47               ///
 48               LOGIN_USER_DOESNT_EXIST,
 49               ///
 50               ///用户帐号被禁用
 51               ///
 52               LOGIN_USER_ACCOUNT_INACTIVE,
 53               ///
 54               ///用户密码不正确
 55               ///
 56               LOGIN_USER_PASSWORD_INCORRECT
 57          }
 58 
 59          ///
 60          ///用户属性定义标志
 61          ///
 62          public enum ADS_USER_FLAG_ENUM
 63          {
 64               ///
 65               ///登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。
 66               ///
 67               ADS_UF_SCRIPT = 0X0001,
 68               ///
 69               ///用户帐号禁用标志
 70               ///
 71               ADS_UF_ACCOUNTDISABLE = 0X0002,
 72               ///
 73               ///主文件夹标志
 74               ///
 75               ADS_UF_HOMEDIR_REQUIRED = 0X0008,
 76               ///
 77               ///过期标志
 78               ///
 79               ADS_UF_LOCKOUT = 0X0010,
 80               ///
 81               ///用户密码不是必须的
 82               ///
 83               ADS_UF_PASSWD_NOTREQD = 0X0020,
 84               ///
 85               ///密码不能更改标志
 86               ///
 87               ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
 88               ///
 89               ///使用可逆的加密保存密码
 90               ///
 91               ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
 92               ///
 93               ///本地帐号标志
 94               ///
 95               ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
 96               ///
 97               ///普通用户的默认帐号类型
 98               ///
 99               ADS_UF_NORMAL_ACCOUNT = 0X0200,
100               ///
101               ///跨域的信任帐号标志
102               ///
103               ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
104               ///
105               ///工作站信任帐号标志
106               ///
107               ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
108               ///
109               ///服务器信任帐号标志
110               ///
111               ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
112               ///
113               ///密码永不过期标志
114               ///
115               ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
116               ///
117               /// MNS 帐号标志
118               ///
119               ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
120               ///
121               ///交互式登录必须使用智能卡
122               ///
123               ADS_UF_SMARTCARD_REQUIRED = 0X40000,
124               ///
125               ///当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
126               ///
127               ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
128               ///
129               ///当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
130               ///
131               ADS_UF_NOT_DELEGATED = 0X100000,
132               ///
133               ///此帐号需要 DES 加密类型
134               ///
135               ADS_UF_USE_DES_KEY_ONLY = 0X200000,
136               ///
137               ///不要进行 Kerberos 预身份验证
138               ///
139               ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
140               ///
141               ///用户密码过期标志
142               ///
143               ADS_UF_PASSWORD_EXPIRED = 0X800000,
144               ///
145               ///用户帐号可委托标志
146               ///
147               ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
148          }
149 
150          public ADHelper()
151          {
152               //
153          }
154 
155          #region GetDirectoryObject
156 
157          ///
158          ///获得DirectoryEntry对象实例,以管理员登陆AD
159          ///
160          ///
161          private static DirectoryEntry GetDirectoryObject()
162          {
163               DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
164               return entry;
165          }
166 
167          ///
168          ///根据指定用户名和密码获得相应DirectoryEntry实体
169          ///
170          ///
171          ///
172          ///
173          private static DirectoryEntry GetDirectoryObject(string userName, string password)
174          {
175               DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);
176               return entry;
177          }
178 
179          ///
180          /// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com
181          ///
182          ///
183          ///
184          private static DirectoryEntry GetDirectoryObject(string domainReference)
185          {
186               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);
187               return entry;
188          }
189 
190          ///
191          ///获得以UserName,Password创建的DirectoryEntry
192          ///
193          ///
194          ///
195          ///
196          ///
197          private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
198          {
199               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
200               return entry;
201          }
202 
203          #endregion
204 
205          #region GetDirectoryEntry
206 
207          ///
208          ///根据用户公共名称取得用户的 对象
209          ///
210          ///
211 用户公共名称 
212          ///如果找到该用户,则返回用户的 对象;否则返回 null
213          public static DirectoryEntry GetDirectoryEntry(string commonName)
214          {
215               DirectoryEntry de = GetDirectoryObject();
216               DirectorySearcher deSearch = new DirectorySearcher(de);
217               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
218               deSearch.SearchScope = SearchScope.Subtree;
219 
220               try
221               {
222                    SearchResult result = deSearch.FindOne();
223                    de = new DirectoryEntry(result.Path);
224                    return de;
225               }
226               catch
227               {
228                    return null;
229               }
230          }
231 
232          ///
233          ///根据用户公共名称和密码取得用户的 对象。
234          ///
235          ///
236 用户公共名称 
237          ///
238 用户密码 
239          ///如果找到该用户,则返回用户的 对象;否则返回 null
240          public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
241          {
242               DirectoryEntry de = GetDirectoryObject(commonName, password);
243               DirectorySearcher deSearch = new DirectorySearcher(de);
244               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
245               deSearch.SearchScope = SearchScope.Subtree;
246 
247               try
248               {
249                    SearchResult result = deSearch.FindOne();
250                    de = new DirectoryEntry(result.Path);
251                    return de;
252               }
253               catch
254               {
255                    return null;
256               }
257          }
258 
259          ///
260          ///根据用户帐号称取得用户的 对象
261          ///
262          ///
263 用户帐号名 
264          ///如果找到该用户,则返回用户的 对象;否则返回 null
265          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
266          {
267               DirectoryEntry de = GetDirectoryObject();
268               DirectorySearcher deSearch = new DirectorySearcher(de);
269               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
270               deSearch.SearchScope = SearchScope.Subtree;
271 
272               try
273               {
274                    SearchResult result = deSearch.FindOne();
275                    de = new DirectoryEntry(result.Path);
276                    return de;
277               }
278               catch
279               {

280                    return null;
281               }
282          }
283 
284          ///
285          ///根据用户帐号和密码取得用户的 对象
286          ///
287          ///
288 用户帐号名 
289          ///
290 用户密码 
291          ///如果找到该用户,则返回用户的 对象;否则返回 null
292          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
293          {
294               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
295               if (de != null)
296               {
297                    string commonName = de.Properties["cn"][0].ToString();
298 
299                    if (GetDirectoryEntry(commonName, password) != null)
300                        return GetDirectoryEntry(commonName, password);
301                    else
302                        return null;
303               }
304               else
305               {
306                    return null;
307               }
308          }
309 
310          ///
311          ///根据组名取得用户组的 对象
312          ///
313          ///
314 组名 
315          ///
316          public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
317          {
318               DirectoryEntry de = GetDirectoryObject();
319               DirectorySearcher deSearch = new DirectorySearcher(de);
320               deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
321               deSearch.SearchScope = SearchScope.Subtree;
322 
323               try
324               {
325                    SearchResult result = deSearch.FindOne();
326                    de = new DirectoryEntry(result.Path);
327                    return de;
328               }
329               catch
330               {
331                    return null;
332               }
333          }
334 
335          #endregion
336 
337          #region GetProperty
338 
339          ///
340          ///获得指定 指定属性名对应的值
341          ///
342          ///
343          ///
344 属性名称 
345          ///属性值
346          public static string GetProperty(DirectoryEntry de, string propertyName)
347          {
348               if(de.Properties.Contains(propertyName))
349               {
350                    return de.Properties[propertyName][0].ToString() ;
351               }
352               else
353               {
354                    return string.Empty;
355               }
356          }
357 
358          ///
359          ///获得指定搜索结果 中指定属性名对应的值
360          ///
361          ///
362          ///
363 属性名称 
364          ///属性值
365          public static string GetProperty(SearchResult searchResult, string propertyName)
366          {
367               if(searchResult.Properties.Contains(propertyName))
368               {
369                    return searchResult.Properties[propertyName][0].ToString() ;
370               }
371               else
372               {
373                    return string.Empty;
374               }
375          }
376 
377          #endregion
378 
379          ///
380          ///设置指定 的属性值
381          ///
382          ///
383          ///
384 属性名称 
385          ///
386 属性值 
387          public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
388          {
389               if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
390               {
391                    if(de.Properties.Contains(propertyName))
392                    {
393                        de.Properties[propertyName][0] = propertyValue; 
394                    }
395                    else
396                    {
397                        de.Properties[propertyName].Add(propertyValue);
398                    }
399               }
400          }
401 
402          ///
403          ///创建新的用户
404          ///
405          ///
406 DN 位置。例如:OU=共享平台 或 CN=Users 
407          ///
408 公共名称 
409          ///
410 帐号 

411          ///
412 密码 
413          ///
414          public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
415          {
416               DirectoryEntry entry = GetDirectoryObject();
417               DirectoryEntry subEntry = entry.Children.Find(ldapDN);
418               DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
419               deUser.Properties["sAMAccountName"].Value = sAMAccountName;
420               deUser.CommitChanges();
421               ADHelper.EnableUser(commonName);
422               ADHelper.SetPassword(commonName, password);
423               deUser.Close();
424               return deUser;
425          }
426 
427          ///
428          ///创建新的用户。默认创建在 Users 单元下。
429          ///
430          ///
431 公共名称 
432          ///
433 帐号 
434          ///
435 密码 
436          ///
437          public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)
438          {
439               return CreateNewUser("CN=Users", commonName, sAMAccountName, password);
440          }
441 
442          ///
443          ///判断指定公共名称的用户是否存在
444          ///
445          ///
446 用户公共名称 
447          ///如果存在,返回 true;否则返回 false
448          public static bool IsUserExists(string commonName)
449          {
450               DirectoryEntry de = GetDirectoryObject();
451               DirectorySearcher deSearch = new DirectorySearcher(de);
452               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";       // LDAP 查询串
453               SearchResultCollection results = deSearch.FindAll();
454 
455               if (results.Count == 0)
456                    return false;
457               else
458                    return true;
459          }
460 
461          ///
462          ///判断用户帐号是否激活
463          ///
464          ///
465 用户帐号属性控制器 
466          ///如果用户帐号已经激活,返回 true;否则返回 false
467          public static bool IsAccountActive(int userAccountControl)
468          {
469               int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
470               int flagExists = userAccountControl & userAccountControl_Disabled;
471 
472               if (flagExists > 0)
473                    return false;
474               else
475                    return true;
476          }
477 
478          ///
479          ///判断用户与密码是否足够以满足身份验证进而登录
480          ///
481          ///
482 用户公共名称 
483          ///
484 密码 
485          ///如能可正常登录,则返回 true;否则返回 false
486          public static LoginResult Login(string commonName, string password)
487          {
488               DirectoryEntry de = GetDirectoryEntry(commonName);
489 
490               if (de != null)
491               {
492                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
493                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
494                    de.Close();
495 
496                    if (!IsAccountActive(userAccountControl))
497                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
498 
499                    if (GetDirectoryEntry(commonName, password) != null)
500                        return LoginResult.LOGIN_USER_OK;
501                    else
502                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
503               }
504               else
505               {
506                    return LoginResult.LOGIN_USER_DOESNT_EXIST; 
507               }
508          }
509 
510          ///
511          ///判断用户帐号与密码是否足够以满足身份验证进而登录
512          ///
513          ///
514 用户帐号 
515          ///
516 密码 
517          ///如能可正常登录,则返回 true;否则返回 false
518          public static LoginResult LoginByAccount(string sAMAccountName, string password)
519          {
520               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
521                    
522               if (de != null)
523               {
524                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
525                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
526                    de.Close();
527 
528                    if (!IsAccountActive(userAccountControl))
529                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
530 
531                    if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
532                        return LoginResult.LOGIN_USER_OK;
533                    else
534                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
535               }
536               else
537               {
538                    return LoginResult.LOGIN_USER_DOESNT_EXIST; 
539               }
540          }
541 
542          ///
543          ///设置用户密码,管理员可以通过它来修改指定用户的密码。
544          ///
545          ///
546 用户公共名称 
547          ///
548 用户新密码 
549          public static void SetPassword(string commonName, string newPassword)
550          {
551               DirectoryEntry de = GetDirectoryEntry(commonName);
552               
553               // 模拟超级管理员,以达到有权限修改用户密码
554               impersonate.BeginImpersonate();
555               de.Invoke("SetPassword", new object[]{newPassword});
556               impersonate.StopImpersonate();
557 
558               de.Close();
559          }
560 
561          ///
562          ///设置帐号密码,管理员可以通过它来修改指定帐号的密码。
563          ///
564          ///
565 用户帐号 
566          ///
567 用户新密码 
568          public static void SetPasswordByAccount(string sAMAccountName, string newPassword)
569          {
570               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
571 
572               // 模拟超级管理员,以达到有权限修改用户密码
573               IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
574               impersonate.BeginImpersonate();
575               de.Invoke("SetPassword", new object[]{newPassword});
576               impersonate.StopImpersonate();
577 
578               de.Close();
579          }
580 
581          ///
582          ///修改用户密码
583          ///
584          ///
585 用户公共名称 
586          ///
587 旧密码 
588          ///
589 新密码 
590          public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword)
591          {
592               // to-do: 需要解决密码策略问题
593               DirectoryEntry oUser = GetDirectoryEntry(commonName);
594               oUser.Invoke("ChangePassword", new Object[]{oldPassword, newPassword});
595               oUser.Close();
596          }
597 
598          ///
599          ///启用指定公共名称的用户
600          ///
601          ///
602 用户公共名称 
603          public static void EnableUser(string commonName)
604          {
605               EnableUser(GetDirectoryEntry(commonName));
606          }
607 
608          ///
609          ///启用指定 的用户
610          ///
611          ///
612          public static void EnableUser(DirectoryEntry de)
613          {
614               impersonate.BeginImpersonate();
615               de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
616               de.CommitChanges();
617               impersonate.StopImpersonate();
618               de.Close();
619          }
620 
621          ///
622          ///禁用指定公共名称的用户
623          ///
624          ///
625 用户公共名称 
626          public static void DisableUser(string commonName)
627          {
628               DisableUser(GetDirectoryEntry(commonName));
629          }
630 
631          ///
632          ///禁用指定 的用户
633          ///
634          ///
635          public static void DisableUser(DirectoryEntry de)
636          {
637               impersonate.BeginImpersonate();
638               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;
639               de.CommitChanges();
640               impersonate.StopImpersonate();
641               de.Close();
642          }
643 
644          ///
645          ///将指定的用户添加到指定的组中。默认为 Users 下的组和用户。
646          ///
647          ///
648 用户公共名称 
649          ///
650 组名 
651          public static void AddUserToGroup(string userCommonName, string groupName)
652           {
653               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
654               DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
655               
656               impersonate.BeginImpersonate();
657               oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
658               oGroup.CommitChanges();
659               impersonate.StopImpersonate();
660 
661               oGroup.Close();
662               oUser.Close();
663          }
664 
665          ///
666          ///将用户从指定组中移除。默认为 Users 下的组和用户。
667          ///
668          ///
669 用户公共名称 
670          ///
671 组名 
672          public static void RemoveUserFromGroup(string userCommonName, string groupName)
673          {
674               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
675               DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
676               
677               impersonate.BeginImpersonate();
678               oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
679               oGroup.CommitChanges();
680               impersonate.StopImpersonate();
681 
682               oGroup.Close();
683               oUser.Close();
684          }
685 
686      }
687 
688      ///
689      ///用户模拟角色类。实现在程序段内进行用户角色模拟。
690      ///
691      public class IdentityImpersonation
692      {
693          [DllImport("advapi32.dll", SetLastError=true)]
694          public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
695 
696          [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
697          public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
698 
699          [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
700          public extern static bool CloseHandle(IntPtr handle);
701 
702          // 要模拟的用户的用户名、密码、域(机器名)
703          private String _sImperUsername;
704          private String _sImperPassword;
705          private String _sImperDomain;
706          // 记录模拟上下文
707          private WindowsImpersonationContext _imperContext;
708          private IntPtr _adminToken;
709          private IntPtr _dupeToken;
710          // 是否已停止模拟
711          private Boolean _bClosed;
712 
713          ///
714          ///构造函数
715          ///
716          ///
717 所要模拟的用户的用户名 
718          ///
719 所要模拟的用户的密码 
720          ///
721 所要模拟的用户所在的域 
722          public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain) 
723          {
724               _sImperUsername = impersonationUsername;
725               _sImperPassword = impersonationPassword;
726               _sImperDomain = impersonationDomain;
727 
728               _adminToken = IntPtr.Zero;
729               _dupeToken = IntPtr.Zero;
730               _bClosed = true;
731          }
732 
733          ///
734          ///析构函数
735          ///
736          ~IdentityImpersonation() 
737          {
738               if(!_bClosed) 
739               {
740                    StopImpersonate();
741               }
742          }
743 
744          ///
745          ///开始身份角色模拟。
746          ///
747          ///
748          public Boolean BeginImpersonate() 
749          {
750               Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);
751                         
752               if(!bLogined) 
753               {
754                    return false;
755               }
756 
757               Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
758 
759               if(!bDuped) 
760               {
761                    return false;
762               }
763 
764               WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
765               _imperContext = fakeId.Impersonate();
766 
767               _bClosed = false;
768 
769               return true;
770          }
771 
772          ///
773          ///停止身分角色模拟。
774          ///
775          public void StopImpersonate() 
776          {
777               _imperContext.Undo();
778               CloseHandle(_dupeToken);
779               CloseHandle(_adminToken);
780               _bClosed = true;
781          }
782      }
783 }
784 =====================================================
785 
786 简单的应用
787 
788 [WebMethod]
789   public string IsAuthenticated(string UserID,string Password)
790   {
791             string _path = "LDAP://" + adm + "/DC=lamda,DC=com,DC=cn";//"LDAP://172.75.200.1/DC=名字,DC=com,DC=cn";
792    string _filterAttribute=null;
793   
794    DirectoryEntry entry = new DirectoryEntry(_path,UserID,Password);
795    
796    try
797    {
798     //Bind to the native AdsObject to force authentication.
799     DirectorySearcher search = new DirectorySearcher(entry);
800     search.Filter = "(SAMAccountName=" + UserID + ")";
801     SearchResult result = search.FindOne();
802     
803     if(null == result)
804     {
805      _filterAttribute="登录失败: 未知的用户名或错误密码.";
806     }
807     else
808     {
809      _filterAttribute="true";
810     }
811    
812    }
813    catch (Exception ex)
814    {
815 //    if(ex.Message.StartsWith("该服务器不可操作")) 
816 //    {
817 //     string mail = ADO.GetConnString("mail");
818 //     entry.Path = "LDAP://"+mail+"/OU=名字,DC=it2004,DC=gree,DC=com,DC=cn";
819 //     try
820 //     { 
821 //      DirectorySearcher search = new DirectorySearcher(entry);
822 //      search.Filter = "(SAMAccountName=" + UserID + ")";
823 //      SearchResult result = search.FindOne();
824 //
825 //      if(null == result)
826 //      {
827 //       _filterAttribute="登录失败: 未知的用户名或错误密码.";
828 //      }
829 //      else
830 //      {
831 //       _filterAttribute="true";
832 //      }
833 //      return _filterAttribute;
834 //   
835 //     }
836 //     catch (Exception ex1)
837 //     {
838 //      return ex1.Message;
839 //     }
840 //     
841 //    }
842 //    else
843      return ex.Message;
844    }
845    return _filterAttribute;
846   }
847   [WebMethod]
848   public string[] LDAPMessage(string UserID)
849   {
850    string _path = "LDAP://"+adm+"/DC=it2004,DC=名字,DC=com,DC=cn";
851    string[] _filterAttribute=new string[5];
852    string[] msg = {"samaccountname","displayname","department","company"};
853 
854    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");
855 
856    
857    try
858    { 
859 
860 
861     Object obj = entry.NativeObject;
862     
863     DirectorySearcher search = new DirectorySearcher(entry);
864     search.Filter = "(SAMAccountName=" + UserID + ")";
865     SearchResult result = search.FindOne();
866 
867     
868     if(null == result)
869     {
870      _filterAttribute[0]="登录失败: 未知的用户名或错误密码.";
871     }
872     else
873     {
874      _filterAttribute[0]="true";  
875      for(int propertyCounter = 1; propertyCounter < 5; propertyCounter++)
876      {
877        
878       if(propertyCounter==4 &&  result.Properties[msg[propertyCounter-1]][0]==null)
879        break;
880       _filterAttribute[propertyCounter]=result.Properties[msg[propertyCounter-1]][0].ToString();
881       
882      }
883     }
884    
885    }
886    catch (Exception ex)
887    {
888     //_filterAttribute[0]=ex.Message;
889    }
890    return _filterAttribute;
891   }
892   [WebMethod]
893   public string[] AllMembers() 
894   {
895    
896    string[] msg;
897    string _path = "LDAP://名字";
898 
899    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");
900    
901 
902    //Bind to the native AdsObject to force authentication.
903    Object obj = entry.NativeObject;
904 
905    System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
906    mySearcher.Filter = "(SAMAccountName=180037)";
907    msg=new string[mySearcher.FindAll().Count];
908    int i=0;
909    foreach(System.DirectoryServices.SearchResult result in mySearcher.FindAll()) 
910    {
911     msg[i++]=result.Path;
912    }
913    return msg;
914   }
915 
916 }

 

转载于:https://www.cnblogs.com/jiewei915/archive/2012/10/29/2744894.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值