Home » Articles

User Roles: authentication at 'Role' level

1. October 2008 by Juliën Hanssens 0 Comments

In VB.NET we can easily query the current Windows user - and which roles are "addressed" to him/her. Long live the My-namespace. In C# it isn't tricky either, it just needs a little deeper digging in the System.Security.Principal namespace.

In the following example we will check if a user is a member of the Administrators group role. If so, then we want to display a button. Otherwise it shouldn't be visible to the user.

// Retrieve the identity of the current user:
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentUser = new WindowsPrincipal(currentIdentity);
 
// Determine if the user belongs to the "Administrator" group:
if (currentUser.IsInRole(WindowsBuiltInRole.Administrator))
{
    // if so, he/she is an Administrator:
    this.button1.Visible = true;
}
else
{
    // if not, too bad - he/she can't access the button:
    this.button1.Visible = false;
}

Using the WindowsIdentity and WindowsPrincipal we can easily retrieve information regarding a Windows user  and it's roles.

Comments are closed