• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 677
  • Last Modified:

Custom Authorization with Windows Authentication

I've tried to write a routine which will assign custom roles from a database. It's not working quite as I hoped, and I reckon I need some help. It is called from the Global.asax Application_AuthenticateRequest event.

I store the custom roles of the user in the database, and keep a DataTable in Application state to save making a connection on every request. A custom error is thrown if the routine cannot find the current user's username in the DataTable. The problem I'm having is that when I add a new user, even though I make certain to update the DataTable and confirm visually that the new user is in there, the routine still throws this custom error. This seems only to be fixed by restarting the app.

'Assign the custom roles to the user. This is done on every request.
    Private Sub AssignUserRoles()

        'Only do this if user is authenticated.
        If Not Request.IsAuthenticated Then
            Throw New Exception("Access denied. ")
        End If

        'Get the essential Windows domain + group. ("MACHINENAME\AppUsers")
        Dim windowsDomainAndGroup As String = AppSettings.WindowsDomain & "\" & AppSettings.WindowsGroup

        'If the user is not in the essential Windows group initially, NO CHANGES will be made to her Roles.
        ' This means also that such a user cannot access the "admin" folder, as the "admin"
        ' role will not get assigned here unless they first belong to the essential Windows group.
        If User.IsInRole(windowsDomainAndGroup) Then

            'Get the user's custom roles from the cached "users" datatable, and
            ' try to assign the user's roles from the cached "users" datatable.
            Dim users As DataTable = CType(Application("users"), DataTable)

            Session("testUsers") = users

                'Get the value in the "Roles" column of the first ((0) - and only) DataRow
                ' in an array of DataRows produced from Selecting from the "users" DataTable
                ' where "Username" = the user's name.
                ' If the username doesn't exist, an IndexOutOfRangeException will occur as there
                ' will be no DataRows in the array. (Thrown below.)
                Dim customRoles As String = users.Select("Username = '" _
                    & User.Identity.Name _
                    & "'")(0)("Roles").ToString()

                'Assign the roles to the user, including the essential Windows group
                ' (as this is not retained when the User is replaced by a New GenericPrincipal).
                HttpContext.Current.User = New System.Security.Principal.GenericPrincipal( _
                    Context.User.Identity, (windowsDomainAndGroup & "," & customRoles).Split(Convert.ToChar(",")))

            Catch ex As System.IndexOutOfRangeException 'username doesn't exist in database.
                Throw New System.Exception("Access denied. Have a superUser (a user able to " _
                    & "configure the database) set your permissions correctly, " _
                    & "or log out of Windows and try again.")

                'Update "users" datatable (used to store their custom roles)
                ' in case it is an old version which is causing the problem.
                ' They can then try again.

            End Try

        End If 'User.IsInRole(windowsDomainAndGroup)

    End Sub

Many thanks,
1 Solution
sumo_the_catAuthor Commented:
Please ignore "Session("testUsers") = users" - don't know how that got in there...
I think your whole routine should go in the authentication event of your login page instead of the global.aspx page:
This is how I obtain a comma seperated value of user roles and then authenticate based on that in the page load of every page heres the authentication routine:

  Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        'Handles the Log In button click
    End Sub
    Private Sub ProcessLoginRequest(ByVal RedirectPage As String)
        Dim Login As String = Me.txtLogin.Text
        Dim Password As String = Me.txtPassword.Text
        Select Case AuthenticateLogin(Login, Password)
            Case 0
                Me.lblMsg.Visible = True
                Me.lblMsg.Text = "Invalid Credentials"
            Case 1
                Dim Roles As String
                Dim authTicket As FormsAuthenticationTicket
                Dim encTicket As String
                Dim cookie As HttpCookie
                Roles = GetRolesString(Login)
                authTicket = New FormsAuthenticationTicket(1, Login, Now(), Now.AddMinutes(30), False, Roles)
                encTicket = FormsAuthentication.Encrypt(authTicket)
                cookie = New HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
        End Select
    End Sub
    Private Function AuthenticateLogin(ByVal Login As String, ByVal Password As String) As Integer
        'Authenticates the user against the database
        Dim cmd As New SqlCommand
        Dim ReturnValue As Integer
        cmd.Connection = New SqlConnection(ConfigurationSettings.AppSettings("EmeraldConnStr"))
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "SynthesisAuthenticateLogin"
        cmd.Parameters.Add(New SqlParameter("@Login", Login))
        cmd.Parameters.Add(New SqlParameter("@Password", Password))
        cmd.Parameters.Add(New SqlParameter("@ReturnCode", DbType.Int32))
        cmd.Parameters("@ReturnCode").Direction = ParameterDirection.ReturnValue
        ReturnValue = CInt(cmd.Parameters("@ReturnCode").Value)
        Return ReturnValue
    End Function
    Private Function GetRolesString(ByVal Login As String) As String
        'Returns a comma-delimited string of the user's roles
        'For testing purposes, you can hard-code the role list and skip the database stuff
        'Return "User"
        Dim cmd As New SqlCommand
        Dim dr As SqlDataReader
        Dim Roles As String
        cmd.Connection = New SqlConnection(ConfigurationSettings.AppSettings("EmeraldConnStr"))
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "SynthesisGetOperatorRoles"
        cmd.Parameters.Add(New SqlParameter("@Login", Login))
        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        If dr.Read Then
            Roles = CStr(dr("RoleList"))
        End If
        dr = Nothing
        Return Roles.ToString
    End Function

And then in the page load to ensure they are a user on each page use:

 Dim authTicket As FormsAuthenticationTicket = CType(HttpContext.Current.User.Identity, FormsIdentity).Ticket()
        HttpContext.Current.User = New GenericPrincipal(User.Identity, Split(authTicket.UserData, ","))

Then you have the user name and role to determine privalege.


Here is an MSDN example that implements custom roles using "Application_AuthenticateRequest event"

How To Implement Role-Based Security with Forms-Based Authentication in Your ASP.NET Application by Using Visual C# .NET
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

sumo_the_catAuthor Commented:
Ok, but it's Integratged Windows Authentication aeros, not forms (as in title). I need some help debugging the code I've written if possible. Thanks, Pete.
It looks to me like the reason the new people are throwing the error is because the datatable in Application state needs to be updated prior to new authentication.  This would explain it working once the application is restarted.  I may have missed the point though.  Let me know...

In whatever event you want:

        With Application
            ' or provide a function to reference the contents and check for
            ' the datatable prior to removing/adding for bettwe control
            .Add("RoleTable", dt)
        End With
One more thing (sorry)...  It would probably be better overall depending on how many users you have hitting your app to nested this functionality within a class instead of the Application State.  Just a suggestion...
sumo_the_catAuthor Commented:
Thanks - good advice. I thought the problem was with the Application state, and considered it might need locking etc., but I've temporarily stuck a direct SQL command in there (getting the roles from the database on every single page request!). The same problem. For some users, it seems I'm not retrieving the roles properly. It's really, really weird. ..

I'm not sure I follow the second point...?

Thanks for your comments; any more appreciated.
The second point was was more or less referencing busier applications.  If you are adding/removing users on a regular basis, or the users themselves can add/remove themselves, it might be more efficient to write a class which would provide the same functionality but would not affect the application state.  This would more than likely get rid of your application state data problem too since each time a user needs to use the class the data is retrieve again, but only then.  If it is your application state, the data is always in memory on the server.  

There are MANY ways to skin a cat (figuratively speaking of course), that's just my two cents.  :)
sumo_the_catAuthor Commented:
Thanks a lot for your help. Thanks to aeros and daffodils too, but i really needed help debugging the actual code. The final answer I discovered (sort of) by myself, which is not interesting to anyone else.  
This message is for hismightiness...or anybody that can help for that matter haha.
I trying to move my windows Authentication into a "Common.cs" files that hold all my shared code.
I'm geting a namespace  errors.
Could you please look at my post


Thanks for the help!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now