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 Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If (User.Identity.IsAuthenticated) And (Not IsNothing(User)) Then

 

Dim Rp As RolePrincipal = DirectCast(User, RolePrincipal)

Dim Info As StringBuilder = 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>”)

 

Dim Roles() As String = Rp.GetRoles()

Dim Role As String

For Each Role In Roles

If Not Role.Equals(String.Empty) Then

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

End If

Next

LabelPrincipalInfo.Text = Info.ToString()

End If

End Sub

 

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

 

Results of querying the RolePrincipal with Windows authentication in VB.NET

Results of querying the RolePrincipal with Windows authentication in VB.NET

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.