Where can I find an example that does the following?
- Pulls a user from Active Directory.
- Gets the groups the user is a member of.
- Gets a list of permissions assigned to each group.
This seems like a simple task but I can't find a solution.
The overall goal is to assign custom permissions and use them to control rights within an application.
If you're on .NET 3.5 and up, 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
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
The last point: permissions. Those aren't stored in Active Directory - and therefore, you can't retrieve those from any AD code.
Permissions are stored on the individual file system items, e.g. files and/or directories - or other objects (like registry keys, etc.). When you have an AD group or user account, you can read it's SID (Security Identifier) property - that SID will show up in ACL's (Access Control Lists) all over Windows - but from the user or group, there's no mechanism to get all permissions it might have anywhere in the machine/server.
Permissions for files and directories can e.g. be retrieved using the .GetAccessControl()
method on the FileInfo
and DirectoryInfo
classes:
FileInfo info = new FileInfo(@"D:\test.txt");
FileSecurity fs = info.GetAccessControl();
DirectoryInfo dir = new DirectoryInfo(@"D:\test\");
DirectorySecurity ds = dir.GetAccessControl();
Deciphering and making sense of those is a whole different story altogether!