Using the following code I can easily see if the supplied user exists in a supplied group.
public static bool IsInGroup(string user, string group)
{
using (var identity = new WindowsIdentity(user))
{
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(group);
}
}
However, given a list of strings like the following:-
User1
User2
User3
Group1
Group2
Group3
Is there any way in c# by looping this list of strings, to check to see if each entry is an AD group or not ?
For example, User3 is actually a group name, but from looking at the list you would think it's a normal AD user.
Is there any way of parsing the name to see if it exists as a group on my AD domain.
I basically want to be able to run through a list of names and groups, and see if a given user name (for example 'Bob') is in the list, or exists in one of the groups in this list, therefore if an entry in the list above is an AD group I want to run a function similar to above to see if the user exists within the group or not.
Go to “Active Directory Users and Computers”. Click on “Users” or the folder that contains the user account. Right click on the user account and click “Properties.” Click “Member of” tab.
To find AD groups with PowerShell, you can use the Get-ADGroup cmdlet. With no parameters, Get-ADGroup will query AD and return all groups in a domain using the Filter parameter. The Filter parameter is required. It exists to limit the groups returned based on various criteria.
Open the properties dialog of the Active Directory group whose objectGUID you need to find, and navigate to the Attribute Editor tab. In this list, in alphabetical order, you can find the objectGUID value for the group.
It isn't too bad. You will need to reference the following Assemblies:
System.DirectoryServices
System.DirectoryServices.Protocols
System.DirectoryServices.AccountManagement
Then you can use something like this:
var groupName = "developers";
using (var context = new PrincipalContext(ContextType.Domain))
{
var groupPrincipal = GroupPrincipal.FindByIdentity(context, groupName);
}
You can change out the PrincipalContext constructor to use ContextType.Machine for the local machine, and if needed you can add the domain name as a second parameter, but for a local domain it should pick it up.
[edit] Also, the FindByIdentity method will return null if it doesn't match. Also, you can get member users and other useful information from the Directory Services.
Check this link out. Essentially turns groups into roles and then you can use it using standard membership provider functionality.
http://slalomdev.blogspot.com/2008/08/active-directory-role-provider.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With