in

ASP.NET Weblogs

This Blog

Syndication

ShowUsYour<Blog>

Irregular expressions regularly

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

Comments

 

Simon Fell said:

You don't need any of this, it all gets done for you, IsInRole will check against the users group membership.
September 28, 2003 7:22 PM
 

Darren Neimke said:


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 ;-)
September 28, 2003 8:48 PM
 

DotNetHelpless said:

How would you list all roles (windows user groups) an identiy is a member of?
January 31, 2004 3:42 PM
 

Pavel said:

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?

June 19, 2008 5:31 AM

Leave a Comment

(required)  
(optional)
(required)  
Add