Attention: We are retiring the ASP.NET Community Blogs. Learn more >

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

6 Comments

  • You don't need any of this, it all gets done for you, IsInRole will check against the users group membership.



  • Yeh, that's true some - but not all - of the time unfortunately. I was testing my app. on a WinXP machine that was not a domain controller and, although I can query the group membership ( as per GetUserRoles() ) the test against IIdentity.IsInRole was always failing.



    So, a little bit of brute force fixed the problem ;-)

  • How would you list all roles (windows user groups) an identiy is a member of?

  • This is necessary when you check against a custom set of roles. For example in a scenario when authentication is done remotely using a web service and the returned result is a set of AD groups. [If done locally then the AD groups should also appear under the IsInRole list -haven't verified myself though.]
    This code is extremely useful when you have a mixed situation, like loccal admin role overrides remote user role membership and similar sci-fi.
    I don't know of a turnkey way to marshall the windows principal from the web service to the local environment and use it instantly there. Do you?

  • can u tell me this Window authentication and authorization on C # >

  • System.Web.Security.Roles.GetRolesForUser(); will give all the roles of the logged in windows user.

Comments have been disabled for this content.