The .NET Framework distributes with a set of IdentityReference classes. An IdentityReference is a reference to a valid Windows identity (which is computer, user accounts or Windows group) that is expressed through a SID. Every time when system administrator creates a user, a group, or he/she set up a new machine with Windows, he/she gets a worldwide unique SID assigned by the system. This SID is used for uniquely identifying system objects. When for example system administrator is adding a user to a group, a reference to the user in the form of a SID gets added to the group’s user list and to the user’s group list.
The .NET Framework includes three classes for SID reference in the System.Security.Principal namespace:
– IdentityReference – is an abstract base class for any class representing a SID and it is the base class for the next two classes.
– SecurityIdentifier – represents the real, unique code of a SID. The SID looks similar to a Universally Unique ID (UUID).
– NTAccount – represents the human-readable string for a SID.
Note: The IdentityReference base class defines a method called Translate that allows you to convert an existing IdentityReference instance from one type to another, such as the conversion from NTAccount to SecurityIdentifier.
You can use the next code lines to show the groups of the currently logged on Windows user account:
if (User is WindowsPrincipal)
{
// 1. Get general user information
WindowsPrincipal principal = (WindowsPrincipal)User;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
// 2. Get the roles for the user
lblInfoText.Text += “<hr/>”;
lblInfoText.Text += “<h2>Roles:</h2>”;
// The property Groups is a collection of IdentityReference objects
foreach (IdentityReference SIDRef in identity.Groups)
{
lblInfoText.Text += “<br/>______________________”;
// Get the system code for the SID
SecurityIdentifier sid = (SecurityIdentifier)SIDRef.Translate(typeof(SecurityIdentifier));
lblInfoText.Text += “<br><b>SID (code): </b>”;
// You can use Value to access the SID code for the SecurityIdentifier
lblInfoText.Text += sid.Value;
// Get the human-readable SID
NTAccount account = (NTAccount)SIDRef.Translate(typeof(NTAccount));
lblInfoText.Text += ” <b>SID (human-readable): </b>”;
// You can use Value to access the readable name of the user or group for the NTAccount instancehe
lblInfoText.Text += account.Value;
}
}
The next picture shows the result: