code_junkie

Determining members of local groups via C#

Nov 10th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. public ArrayList Groups(string userDn, bool recursive)
  2. {
  3. ArrayList groupMemberships = new ArrayList();
  4. return AttributeValuesMultiString("memberOf", userDn,
  5. groupMemberships, recursive);
  6. }
  7.  
  8. public ArrayList AttributeValuesMultiString(string attributeName,
  9. string objectDn, ArrayList valuesCollection, bool recursive)
  10. {
  11. DirectoryEntry ent = new DirectoryEntry(objectDn);
  12. PropertyValueCollection ValueCollection = ent.Properties[attributeName];
  13. IEnumerator en = ValueCollection.GetEnumerator();
  14.  
  15. while (en.MoveNext())
  16. {
  17. if (en.Current != null)
  18. {
  19. if (!valuesCollection.Contains(en.Current.ToString()))
  20. {
  21. valuesCollection.Add(en.Current.ToString());
  22. if (recursive)
  23. {
  24. AttributeValuesMultiString(attributeName, "LDAP://" +
  25. en.Current.ToString(), valuesCollection, true);
  26. }
  27. }
  28. }
  29. }
  30. ent.Close();
  31. ent.Dispose();
  32. return valuesCollection;
  33. }
  34.  
  35. public static bool IsUserInGroup(string username, string groupname, ContextType type)
  36. {
  37. PrincipalContext context = new PrincipalContext(type);
  38.  
  39. UserPrincipal user = UserPrincipal.FindByIdentity(
  40. context,
  41. IdentityType.SamAccountName,
  42. username);
  43. GroupPrincipal group = GroupPrincipal.FindByIdentity(
  44. context, groupname);
  45.  
  46. return user.IsMemberOf(group);
  47. }
  48.  
  49. private int validateUserActiveDirectory()
  50. {
  51. IntPtr token = IntPtr.Zero;
  52. int DBgroupLevel = 0;
  53.  
  54. // make sure you're yourself -- recommended at msdn http://support.microsoft.com/kb/248187
  55. RevertToSelf();
  56.  
  57. if (LogonUser(txtUserName.Value, propDomain, txtUserPass.Text, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, token) != 0) {
  58. // ImpersonateLoggedOnUser not required for us -- we are not doing impersonated stuff, but leave it here for completeness.
  59. //ImpersonateLoggedOnUser(token);
  60. // do impersonated stuff
  61. // end impersonated stuff
  62.  
  63. // ensure that we are the original user
  64. CloseHandle(token);
  65. RevertToSelf();
  66.  
  67. System.Security.Principal.IdentityReferenceCollection groups = Context.Request.LogonUserIdentity.Groups;
  68. IdentityReference translatedGroup = default(IdentityReference);
  69.  
  70. foreach (IdentityReference g in groups) {
  71. translatedGroup = g.Translate(typeof(NTAccount));
  72. if (translatedGroup.Value.ToLower().Contains("desired group")) {
  73. inDBGroup = true;
  74. return 1;
  75. }
  76. }
  77. }
  78. else {
  79. return 0;
  80. }
  81. }
Add Comment
Please, Sign In to add comment