See if a user is part of an Active Directory group in C # + Asp.net

I need a way to find out if a user is part of an active directory group from my .Net 3.5 asp.net C # application.

I am using the standard ldap authentication example from msdn, but I really don't see how to verify the group.

+43
c # active-directory active-directory-group
Feb 03 '10 at 0:50
source share
13 answers

With 3.5 and System.DirectoryServices.AccountManagement this is a little cleaner:

public List<string> GetGroupNames(string userName) { var pc = new PrincipalContext(ContextType.Domain); var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc); var result = new List<string>(); src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); return result; } 
+38
Feb 03 '10 at 1:01
source share

Nick Craver's solution does not work for me in .NET 4.0. I get an AppDomain unload error message. Instead, I used this (we only have one domain). This will test group groups as well as direct group membership.

 using System.DirectoryServices.AccountManagement; using System.Linq; ... using (var ctx = new PrincipalContext(ContextType.Domain, yourDomain)) { using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, yourGroup)) { bool isInRole = grp != null && grp .GetMembers(true) .Any(m => m.SamAccountName == me.Identity.Name.Replace(yourDomain + "\\", "")); } } 
+19
Jun 14 '10 at 17:35
source share

The code below will work in .net 4.0

 private static string[] GetGroupNames(string userName) { List<string> result = new List<string>(); using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")) { using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc)) { src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); } } return result.ToArray(); } 
+15
Dec 08 '11 at 2:09 p.m.
source share

Simplest solution

 PrincipalContext pc = new PrincipalContext((Environment.UserDomainName == Environment.MachineName ? ContextType.Machine : ContextType.Domain), Environment.UserDomainName); GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, "{GroupName}"); UserPrincipal up = UserPrincipal.FindByIdentity(pc, Environment.UserName); up.IsMemberOf(gp); 
+10
Mar 20 '13 at 22:44
source share

This method can be useful if you are trying to determine if the current Windows authenticated user is in a specific role.

 public static bool CurrentUserIsInRole(string role) { try { return System.Web.HttpContext.Current.Request .LogonUserIdentity .Groups .Any(x => x.Translate(typeof(NTAccount)).ToString() == role); } catch (Exception) { return false; } } 
+7
Sep 06 '13 at 17:18
source share

It depends on what you mean if the user is in an AD group. In AD, groups can be a security group or a distribution group. Even for security groups, this depends on whether groups such as Domain Users or Users should be included in the membership check.

IsUserInSecurityGroup will only check security groups and will work for primary group groups such as Domain Users and Users, not distribution groups. It will also solve the problem with nested groups. IsUserInAllGroup will also check distribution groups, but I'm not sure if you run into permission problems. If you do, use the service account located in WAAG ( See MSDN )

The reason I am not using UserPrincipal.GetAuthorizedGroups () is because it has a lot of problems, such as requiring that the calling account be in WAAG and require that there is no entry in SidHistory ( See David Thomas comment )

 public bool IsUserInSecurityGroup(string user, string group) { return IsUserInGroup(user, group, "tokenGroups"); } public bool IsUserInAllGroup(string user, string group) { return IsUserInGroup(user, group, "tokenGroupsGlobalAndUniversal"); } private bool IsUserInGroup(string user, string group, string groupType) { var userGroups = GetUserGroupIds(user, groupType); var groupTokens = ParseDomainQualifiedName(group, "group"); using (var groupContext = new PrincipalContext(ContextType.Domain, groupTokens[0])) { using (var identity = GroupPrincipal.FindByIdentity(groupContext, IdentityType.SamAccountName, groupTokens[1])) { if (identity == null) return false; return userGroups.Contains(identity.Sid); } } } private List<SecurityIdentifier> GetUserGroupIds(string user, string groupType) { var userTokens = ParseDomainQualifiedName(user, "user"); using (var userContext = new PrincipalContext(ContextType.Domain, userTokens[0])) { using (var identity = UserPrincipal.FindByIdentity(userContext, IdentityType.SamAccountName, userTokens[1])) { if (identity == null) return new List<SecurityIdentifier>(); var userEntry = identity.GetUnderlyingObject() as DirectoryEntry; userEntry.RefreshCache(new[] { groupType }); return (from byte[] sid in userEntry.Properties[groupType] select new SecurityIdentifier(sid, 0)).ToList(); } } } private static string[] ParseDomainQualifiedName(string name, string parameterName) { var groupTokens = name.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries); if (groupTokens.Length < 2) throw new ArgumentException(Resources.Exception_NameNotDomainQualified + name, parameterName); return groupTokens; } 
+4
Jan 30 '13 at 21:07
source share

It looks a lot easier:

 public bool IsInRole(string groupname) { var myIdentity = WindowsIdentity.GetCurrent(); if (myIdentity == null) return false; var myPrincipal = new WindowsPrincipal(myIdentity); var result = myPrincipal.IsInRole(groupname); return result; } 
+3
Apr 07 '15 at 23:11
source share

How about this

How to record an LDAP request to check if a user is a member of a group?

+2
Feb 03 2018-10-02T00
source share

Here are my 2 cents.

  static void CheckUserGroup(string userName, string userGroup) { var wi = new WindowsIdentity(userName); var wp = new WindowsPrincipal(wi); bool inRole = wp.IsInRole(userGroup); Console.WriteLine("User {0} {1} member of {2} AD group", userName, inRole ? "is" : "is not", userGroup); } 
+2
Mar 30 '15 at 15:58
source share

You can try the following code:

 public bool Check_If_Member_Of_AD_Group(string username, string grouptoCheck, string domain, string ADlogin, string ADpassword) {   try {       string EntryString = null;    EntryString = "LDAP://" + domain;       DirectoryEntry myDE = default(DirectoryEntry);       grouptoCheck = grouptoCheck.ToLower();          myDE = new DirectoryEntry(EntryString, ADlogin, ADpassword);       DirectorySearcher myDirectorySearcher = new DirectorySearcher(myDE);       myDirectorySearcher.Filter = "sAMAccountName=" + username;       myDirectorySearcher.PropertiesToLoad.Add("MemberOf");       SearchResult myresult = myDirectorySearcher.FindOne();       int NumberOfGroups = 0;       NumberOfGroups = myresult.Properties["memberOf"].Count - 1;       string tempString = null;       while ((NumberOfGroups >= 0)) {           tempString = myresult.Properties["MemberOf"].Item[NumberOfGroups];      tempString = tempString.Substring(0, tempString.IndexOf(",", 0));           tempString = tempString.Replace("CN=", "");           tempString = tempString.ToLower();      tempString = tempString.Trim();           if ((grouptoCheck == tempString)) {                        return true;      }                  NumberOfGroups = NumberOfGroups - 1;    }            return false;  }  catch (Exception ex) {       System.Diagnostics.Debugger.Break();  }  //HttpContext.Current.Response.Write("Error: <br><br>" & ex.ToString) } 
+1
Feb 03 2018-10-02T00
source share
Brandon Johnson, I liked it, I used what you had, but made the following change:
 private static string[] GetGroupNames(string domainName, string userName) { List<string> result = new List<string>(); using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName)) { using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(principalContext, userName).GetGroups(principalContext)) { src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); } } return result.ToArray(); } 
+1
Aug 07 2018-12-12T00:
source share
 var context = new PrincipalContext(ContextType.Domain, {ADDomain}, {ADContainer}); var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, {AD_GROUP_NAME}); var user = UserPrincipal.FindByIdentity(context, {login}); bool result = user.IsMemberOf(group); 
0
Sep 14 '16 at 13:54 on
source share

If you want to check membership in user groups, including nested groups that are indirectly related to the parent group of the user, you can try using the "tokenGroups" properties, as shown below:

 Using System.DirectoryServices

  public static bool IsMemberOfGroupsToCheck (string DomainServer, string LoginID, string LoginPassword)
         {
             string UserDN = "CN = John.Doe-A, OU = Administration Accounts, OU = User Directory, DC = ABC, DC = com"
             string ADGroupsDNToCheck = "CN = ADGroupTocheck, OU = Administration Groups, OU = Group Directory, DC = ABC, DC = com";

             byte [] sid, parentSID;
             bool check = false;
             DirectoryEntry parentEntry;
             DirectoryEntry basechildEntry;
             string octetSID;

                 basechildEntry = new DirectoryEntry ("LDAP: //" + DomainServer + "/" + UserDN, LoginID, LoginPassword);
                 basechildEntry.RefreshCache (new String [] {"tokenGroups"});

                 parentEntry = new DirectoryEntry ("LDAP: //" + DomainServer + "/" + ADGroupsDNToCheck, LoginID, LoginPassword);
                 parentSID = (byte []) parentEntry.Properties ["objectSID"]. Value;
                 octetSID = ConvertToOctetString (parentSID, false, false);

                 foreach (Object GroupSid in basechildEntry.Properties ["tokenGroups"])
                 {
                     sid = (byte []) GroupSid;
                     if (ConvertToOctetString (sid, false, false) == octetSID)
                     {
                         check = true;
                         break;
                     }
                 }

                 basechildEntry.Dispose ();
                 parentEntry.Dispose ();

                 return check;
         }
0
Sep 21 '16 at 4:39 on
source share



All Articles