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:
- The user himself.
- The groups for which he is a direct member
- The nested groups for which he is an indirect user
- 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
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.
GetAuthorizationGroupsreturns 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 useDirectoryEntryto accesstokenGroupsattribute.UPDATE
To check whether the current user is in
NT AUTHORITY\INTERACTIVEorLOCAL, we can useWindowsIdentity.Groups, which retrieves the current logon token directly. Note that the membership ofNT AUTHORITY\INTERACTIVEandLOCALare 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 ofNT AUTHORITY\REMOTE INTERACTIVE LOGONbecause I was logging on via remote desktop.I am sorry that I don’t know any way to get the
NT AUTHORITY\INTERACTIVEmembership 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.