User/Group Permissions in Active Directory

后端 未结 1 1859
难免孤独
难免孤独 2021-02-04 10:51

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
1条回答
  •  既然无缘
    2021-02-04 11:09

    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!

    0 讨论(0)
提交回复
热议问题