Saturday, June 19, 2010

Determine Groups of a User

In C# one can read-out the groups, which the currently logged in user belongs to, via the WindowsIdentity class, which was introduced in the previous post:
foreach (System.Security.Principal.IdentityReference group in System.Security.Principal.WindowsIdentity.GetCurrent().Groups)
{
    MessageBox.Show(group.ToString());
}
This example outputs only cryptical names though, like {S-1-1-0}.
These numbers are the so called SIDs (Security Identifiers) of the group.
Luckily they can be translated in a different type via the function Translate(), possible types have to stem from the class System.Security.Principal.
If we take the type NTAccount, the groups are shown in a readable format:
foreach (System.Security.Principal.IdentityReference group in System.Security.Principal.WindowsIdentity.GetCurrent().Groups)
{
    MessageBox.Show((group.Translate(typeof(System.Security.Principal.NTAccount))).ToString());
}

Now {S-1-1-0} becomes EVERYONE.

No comments:

Post a Comment