Marcel Gosselin
Marcel Gosselin

Reputation: 4716

How to obtain all the security identifiers (SID) that match a Windows user?

Using .NET, I would like to programmatically get a list of all the groups for which a Windows user is a member as well as all other SID (Security identifiers) that represent a logged in user. The resulting list should contain:

  1. The user himself.
  2. The groups for which he is a direct member
  3. The nested groups for which he is an indirect user
  4. The WellKnownSidTypes that match. For example:
    • Everyone
    • NT AUTHORITY\Authenticated Users
    • ...

The first item is trivial and I can already retrieve points 2 and 3 by using System.DirectoryServices and the attribute tokenGroups on the DirectoryEntry representing my user like this example.

Can somebody find an (easy) way to do this

Upvotes: 0

Views: 3013

Answers (1)

Harvey Kwok
Harvey Kwok

Reputation: 11873

If you want an easy way, I would say UserPrincipal.GetAuthorizationGroups is really easy. The only thing is that you can find it only in .NET 3.5 or later.

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "YourUser"))
    {
        foreach (Principal p in user.GetAuthorizationGroups())
        {
             Console.WriteLine(p.Name);
        }
    }
 }

GetAuthorizationGroups returns you all the nested groups, including the Well known SID. It tries different ways of retrieving the nested group information. Indeed, one of the approaches it used is to use DirectoryEntry to access tokenGroups attribute.

UPDATE

To check whether the current user is in NT AUTHORITY\INTERACTIVE or LOCAL, we can use WindowsIdentity.Groups, which retrieves the current logon token directly. Note that the membership of NT AUTHORITY\INTERACTIVE and LOCAL are determined at runtime. The user is assigned to these groups based on the fact that you are logging onto that system now. Similarly, on my Windows 7, I can see my current logon user is also a member of NT AUTHORITY\REMOTE INTERACTIVE LOGON because I was logging on via remote desktop.

 WindowsIdentity id = WindowsIdentity.GetCurrent();
 foreach (var group in id.Groups)
 {
     Console.WriteLine(((NTAccount)group.Translate(typeof(NTAccount))).Value);
 }

I am sorry that I don't know any way to get the NT AUTHORITY\INTERACTIVE membership for any arbitrary users. I suspect there is no such way because this type of group membership is determined at the runtime only when that user is really logging on.

Upvotes: 2

Related Questions