Validate username and security group in Active Directory


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.