How to use the Roles API with Windows authentication in ASP.NET in C#

The roles API  ships a provider that integrates with Windows roles for Windows authentication: the WindowsTokenRoleProvider. This provider retrieves the Windows group membership information for the currently logged-on user and provides it for your application. When using the WindowsTokenRoleProvider, you have to configure your application using Windows authentication and then configure the WindowsTokenRoleProvider as follows:

 

<configuration>

<system.web>

<authentication mode=”Windows”/>

<authorization>

<deny users=”?” />

</authorization>

<roleManager enabled=”true”

cacheRolesInCookie=”false”

defaultProvider=”WindowsRoles”>

<providers>

<add name=”WindowsRoles”

type=”System.Web.Security.WindowsTokenRoleProvider” />

</providers>

</roleManager>

</system.web>

</configuration>

 

In this case, the user is authenticated through Windows authentication. The RoleManagerModule automatically creates an instance of RolePrincipal and associates it with the HttpContext.Current.User property. Therefore, you can use the RolePrincipal as follows:

 

protected void Page_Load(object sender, EventArgs e)

{

if ((User != null) && (User.Identity.IsAuthenticated))

{

RolePrincipal rp = (RolePrincipal)User;

StringBuilder Info = new StringBuilder();

Info.AppendFormat(“<h2>Welcome {0}!</h2>”, User.Identity.Name);

Info.AppendFormat(“<b>Provider: </b>{0}<br>”, rp.ProviderName);

Info.AppendFormat(“<b>Version: </b>{0}<br>”, rp.Version);

Info.AppendFormat(“<b>Expiration: </b>{0}<br>”, rp.ExpireDate);

Info.AppendFormat(“<b>Roles: </b><br>”);

string[] Roles = rp.GetRoles();

foreach (string role in Roles)

{

if (!role.Equals(string.Empty))

Info.AppendFormat(“-) {0}<br>”, role);

}

LabelPrincipalInfo.Text = Info.ToString();

}

}

 

You can see the result of the previous code in the next picture.

 

Results of querying the RolePrincipal with Windows authentication in C#

Results of querying the RolePrincipal with Windows authentication in C#

 

Important notes:

You should not use Windows groups for authorization in your application directly except for a few of the built-in groups such as the Administrators group, because:

– Windows groups other than the built-in groups depend on the name of the domain or machine on which they exist.

– In most cases, Windows groups in a domain are structured according to the organizational and network management requirements of the enterprise, but these requirements often do not map to the application requirements.

– Structuring application roles independently from the network groups makes your application more flexible and usable across multiple types of network structures.

In other words it’s better to define roles that are specific to your application.