User/Group Permissions in Active Directory

2019-03-13 10:36发布

Where can I find an example that does the following?

  1. Pulls a user from Active Directory.
  2. Gets the groups the user is a member of.
  3. 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.

1条回答
混吃等死
2楼-- · 2019-03-13 11:22

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:

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!

查看更多
登录 后发表回答