Windows Authentication with Role based authorization
I've done a fair bit with ASP.NET security using the FormsAuthentication provider but not much at all with Windows authentication. I'm currently building an app. “out-of-hours” that needed to use integrated Windows authentication and also use Role based authorization based on the users Windows Group membership. Here is a little piece of code that I put together to hook the Windows groups into the roles of the IPrincipal in the application:
[snipped from Global.asax]
Sub WindowsAuthentication_Authenticate(ByVal sender As Object, ByVal e As WindowsAuthenticationEventArgs) Dim roleStrng() As String = GetUserRoles()
e.User = New GenericPrincipal(e.Identity, roleStrng)
End Sub Private Function GetUserRoles() As String()
Dim myDomain As AppDomain = Thread.GetDomain()
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim al As New ArrayList
Dim myPrincipal As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)
Dim wbirFields As Array = [Enum].GetValues(GetType(WindowsBuiltInRole))
Dim roleName As Object
For Each roleName In wbirFields
Try
If myPrincipal.IsInRole(CType(roleName, WindowsBuiltInRole)) Then
al.Add(roleName.ToString())
End If
Catch
End Try
Next roleName
Return CType(al.ToArray(GetType(String)), String())
End Function