Custom Authorization with Windows Authentication

Posted on 2004-09-13
Medium Priority
Last Modified: 2012-05-05
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,
Question by:sumo_the_cat

Author Comment

ID: 12048331
Please ignore "Session("testUsers") = users" - don't know how that got in there...
LVL 17

Expert Comment

ID: 12048446
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.



Expert Comment

ID: 12049340
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 12049557
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.

Accepted Solution

hismightiness earned 2000 total points
ID: 12065694
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

Expert Comment

ID: 12065722
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...

Author Comment

ID: 12074348
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.

Expert Comment

ID: 12075242
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.  :)

Author Comment

ID: 12106009
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.  

Expert Comment

ID: 13141795
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!

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses
Course of the Month12 days, 19 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question