How to Get the Groups of a User in Active Directory? (C#, ASP.NET)

How to get the groups of a user in Active Directory? (c#, asp.net)

If you're on .NET 3.5 or up, you can use the new System.DirectoryServices.AccountManagement (S.DS.AM) namespace which makes this a lot easier than it used to be.

Read all about it here: Managing Directory Security Principals in the .NET Framework 3.5

Update: older MSDN magazine articles aren't online anymore, unfortunately - you'll need to download the CHM for the January 2008 MSDN magazine from Microsoft and read the article in there.

Basically, you need to have a "principal context" (typically your domain), a user principal, and then you get its groups very easily:

public List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();

// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);

// if found - grab its groups
if(user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

// iterate over all groups
foreach(Principal p in groups)
{
// make sure to add only group principals
if(p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}

return result;
}

and that's all there is! You now have a result (a list) of authorization groups that user belongs to - iterate over them, print out their names or whatever you need to do.

Update: In order to access certain properties, which are not surfaced on the UserPrincipal object, you need to dig into the underlying DirectoryEntry:

public string GetDepartment(Principal principal)
{
string result = string.Empty;

DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);

if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}

return result;
}

Update #2: seems shouldn't be too hard to put these two snippets of code together.... but ok - here it goes:

public string GetDepartment(string username)
{
string result = string.Empty;

// if you do repeated domain access, you might want to do this *once* outside this method,
// and pass it in as a second parameter!
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);

// if user is found
if(user != null)
{
// get DirectoryEntry underlying it
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);

if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
}

return result;
}

Return a list of all Active Directory groups a user belongs to in string[ ]

This should do the trick.

using System.DirectoryServices.AccountManagement;

public static string[] GetGroups(string username)
{
string[] output = null;

using (var ctx = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(ctx, username))
{
if (user != null)
{
output = user.GetGroups() //this returns a collection of principal objects
.Select(x => x.SamAccountName) // select the name. you may change this to choose the display name or whatever you want
.ToArray(); // convert to string array
}
}

return output;
}

How to get AD User Groups for user in Asp.Net?

You cannot do this in one step, as groups are also separate AD entries with properties.

So in the first run you should get the group names a user is in and fill them in a list of some kind.

The second step is to go through all of the group names and query them one by one to get the group properties (like distinguishedname, and so on) and collect it to some kind of structure.

C# get groups that a user is a member of in Active Directory

You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
// get the user's groups
var groups = user.GetAuthorizationGroups();

foreach(GroupPrincipal group in groups)
{
// do whatever you need to do with those groups
}
}

}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

ASP.NET How to get List of Groups in Active Directory

Check out System.DirectoryServices (An ASP.NET 2.0 reference):

C#-example to get groups:

using System.DirectoryServices; 

public class test
{

private void main()
{
foreach (string @group in GetGroups())
{
Debug.Print(@group);
}
}

public List<string> GetGroups()
{
DirectoryEntry objADAM = default(DirectoryEntry);
// Binding object.
DirectoryEntry objGroupEntry = default(DirectoryEntry);
// Group Results.
DirectorySearcher objSearchADAM = default(DirectorySearcher);
// Search object.
SearchResultCollection objSearchResults = default(SearchResultCollection);
// Results collection.
string strPath = null;
// Binding path.
List<string> result = new List<string>();

// Construct the binding string.
strPath = "LDAP://stefanserver.stefannet.local";
//Change to your ADserver

// Get the AD LDS object.
try
{
objADAM = new DirectoryEntry(strPath);
objADAM.RefreshCache();
}
catch (Exception e)
{
throw e;
}

// Get search object, specify filter and scope,
// perform search.
try
{
objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(&(objectClass=group))";
objSearchADAM.SearchScope = SearchScope.Subtree;
objSearchResults = objSearchADAM.FindAll();
}
catch (Exception e)
{
throw e;
}

// Enumerate groups
try
{
if (objSearchResults.Count != 0)
{
foreach (SearchResult objResult in objSearchResults)
{
objGroupEntry = objResult.GetDirectoryEntry();
result.Add(objGroupEntry.Name);
}
}
else
{
throw new Exception("No groups found");
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}

return result;
}

}

VB-example to get groups:

Imports System.DirectoryServices

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each group As String In GetGroups()
Debug.Print(group)
Next
End Sub

Public Function GetGroups() As List(Of String)
Dim objADAM As DirectoryEntry ' Binding object.
Dim objGroupEntry As DirectoryEntry ' Group Results.
Dim objSearchADAM As DirectorySearcher ' Search object.
Dim objSearchResults As SearchResultCollection ' Results collection.
Dim strPath As String ' Binding path.
Dim result As New List(Of String)

' Construct the binding string.
strPath = "LDAP://stefanserver.stefannet.local" 'Change to your ADserver

' Get the AD LDS object.
Try
objADAM = New DirectoryEntry(strPath)
objADAM.RefreshCache()
Catch e As Exception
Throw e
End Try

' Get search object, specify filter and scope,
' perform search.
Try
objSearchADAM = New DirectorySearcher(objADAM)
objSearchADAM.Filter = "(&(objectClass=group))"
objSearchADAM.SearchScope = SearchScope.Subtree
objSearchResults = objSearchADAM.FindAll()
Catch e As Exception
Throw e
End Try

' Enumerate groups
Try
If objSearchResults.Count <> 0 Then
Dim objResult As SearchResult
For Each objResult In objSearchResults
objGroupEntry = objResult.GetDirectoryEntry
result.Add(objGroupEntry.Name)
Next objResult
Else
Throw New Exception("No groups found")
End If
Catch e As Exception
Throw New Exception(e.Message)
End Try

Return result
End Function
End Class

How to get all the AD groups for a particular user?

Just query the "memberOf" property and iterate though the return, example:

            search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder(); //stuff them in | delimited

SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
String dn;
int equalsIndex, commaIndex;

for (int propertyCounter = 0; propertyCounter < propertyCount;
propertyCounter++)
{
dn = (String)result.Properties["memberOf"][propertyCounter];

equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1),
(commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}

return groupNames.ToString();

This just stuffs the group names into the groupNames string, pipe delimited, but when you spin through you can do whatever you want with them

How I can find a user in Active Directory Group with SubGroups?

Didn't try that but does adding this to the filter help?
http://ldapwiki.willeke.com/wiki/1.2.840.113556.1.4.1941

e.g.

(&(objectClass=user)(sAMAccountName=*" + username + "*)(memberof:1.2.840.113556.1.4.1941:=CN=GastzugangUser,OU=SubFolderB,OU=FolderB,DC=company,DC=com))";


Related Topics



Leave a reply



Submit