验证Active Directory中的用户名和安全组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证Active Directory中的用户名和安全组相关的知识,希望对你有一定的参考价值。

  1. public static bool IsUserInDomain(string userName)
  2. {
  3. string name = userName;
  4. bool isInDomain = false;
  5. if (name.IndexOf(@"", StringComparison.OrdinalIgnoreCase) != -1)
  6. name = name.Substring(name.IndexOf(@"", StringComparison.OrdinalIgnoreCase) + 1);
  7.  
  8. string ADpath = System.Configuration.ConfigurationManager.AppSettings["ADPath"];
  9. string ADusername = System.Configuration.ConfigurationManager.AppSettings["ADUser"];
  10. string ADpassword = System.Configuration.ConfigurationManager.AppSettings["ADPassword"];
  11. string securityGroup = System.Configuration.ConfigurationManager.AppSettings["ADSecurityGroup"];
  12.  
  13. DirectoryEntry de = new DirectoryEntry { Path = ADpath, Username = ADusername, Password = ADpassword };
  14.  
  15. DirectorySearcher searcher = new DirectorySearcher(de);
  16. // "!userAccountControl:1.2.840.113556.1.4.803:=2" is a check for enabled users only
  17. searcher.Filter = "(&(&((objectClass=user)(objectClass=person))(sAMAccountName=" + userName + ")(!userAccountControl:1.2.840.113556.1.4.803:=2)))";
  18.  
  19. // Is the user found?
  20. SearchResult sr = searcher.FindOne();
  21. if (sr != null)
  22. {
  23. // Find the Security group
  24. searcher = new DirectorySearcher(de);
  25. searcher.Filter = "(&(objectCategory=group)(sAMAccountName=" + securityGroup + "))";
  26. searcher.PropertiesToLoad.Add("distinguishedname");
  27.  
  28. foreach (SearchResult item in searcher.FindAll())
  29. {
  30. // Get the DN from the group
  31. if (item.Properties["distinguishedname"].Count > 0)
  32. {
  33. String dn = item.Properties["distinguishedname"][0].ToString();
  34. searcher = new DirectorySearcher(de);
  35. searcher.Filter = "(&(sAMAccountName=" + userName + ")(memberOf=" + dn + "))";
  36. SearchResult userAndSecurityGroup = searcher.FindOne();
  37. if (userAndSecurityGroup != null)
  38. {
  39. isInDomain = true;
  40. break;
  41. }
  42. }
  43. }
  44. }
  45.  
  46. return isInDomain;
  47. }

以上是关于验证Active Directory中的用户名和安全组的主要内容,如果未能解决你的问题,请参考以下文章

根据 ASP.NET Windows 身份验证的用户名与 Active Directory 中的登录名不匹配

为啥 Active Directory 验证最后一个密码?

C# 中的 LDAP 和 Active Directory 身份验证

如何从 sharepoint 2013 Web 服务和 Active Directory 对用户进行身份验证

具有自定义角色和 Active Directory 的 ASP MVC 5 Windows 身份验证

使用 Spring-boot Application 中的 Spring Security 使用 Active Directory(使用 AD 域)对用户进行身份验证时出现问题