X
    Categories: ASP.NET

Forms Authentication in ASP.NET 2.0 without Membership Provider

The membership provider is a new feature in ASP.NET 2.0 and helps web developers quickly and easily  implement forms authentication and authorization in their web applications. But what if you can’t use the membership provider in your applications? For example, my company implements a single sign-on system for authentication (many companies have the similar single sign-on system), and the user who is accessing our web application  is redirected to the single sign-on page for authentication. Once authenticated, the user will be redirected back to the original application with some security tokens appended in the query string representing the user’s identity. Then our web application will pick up the tokens and start from there as far as the authorization is concerned. So here we can’t use the built-in membership provider in our web applications. Then, in this kind of scenario, how to make sure that the user is authenticated?

Some of the developer in my department use some session variables to store the returned security tokens after the user is authenticated, then check the session variables at each page that needs authentication. If the session variables do not exist, then redirect the user back to the sign in page for authentication. Although it might seem to be simple to implement, it is actually a bad implementation and hard to maintain.

A better implementation is to take advantage of the Global.asax file in the web application. Here is how to implement it (assume the whole application needs to be authenticated):

1. Configuration of web.config

By default, the web.config file contains a section titled <system.web>, where you can insert the following code in it to turn on Forms Authentication in your application:

<authentication mode=”Forms” >
        <forms loginUrl =”Login.aspx”
               protection =”All”
               timeout=”15″
               name=”.ASPXAUTH”
               path=”/”
               requireSSL=”false”
               slidingExpiration =”false”
               defaultUrl =”Default.aspx”
               cookieless =”UseCookies”
               enableCrossAppRedirects =”false” />
</authentication>

The default attribute values are described here.

2. Configuration of Global.asax

With VB.NET, insert the following code in Application_AuthenticateRequest(Object sender, EventArgs e) Sub:

  Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ‘ Fires upon attempting to authenticate the use
        If (HttpContext.Current.Request.IsAuthenticated) Then
            If (HttpContext.Current.User IsNot Nothing) Then
                If (TypeOf (HttpContext.Current.User.Identity) Is FormsIdentity) Then
                    Dim cookieName As String = FormsAuthentication.FormsCookieName
                    Dim cookie As HttpCookie = Context.Request.Cookies(cookieName)
                    Dim authTicket As FormsAuthenticationTicket
                    authTicket = FormsAuthentication.Decrypt(cookie.Value)
                    Dim userData As String = authTicket.UserData
                    Dim roles() As String = userData.Split(“|”)
                    Dim id As FormsIdentity = New FormsIdentity(authTicket)
                    Dim principal As GenericPrincipal = New GenericPrincipal(id, roles)

                    HttpContext.Current.User = principal

                End If
            End If
        End If
    End Sub

3. Event Handler of Login.aspx

The forms authentication cookie is original created and stored when user click the “Login” button on the Login.aspx page. The login button event handler should look something like:

Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs)
     Dim userData As String = String.Empty
     userData = Me.getUserPermissionsByUsername(Me.txtUsername.Text)
     Me.doFormsAuthentication(Me.txtUsername.Text, userData)
End Sub

Where getUserPermissionsByUsername is a function that retrieves the user’s permission roles and returns a limited string, such as “System Administrator|Moderator”. doFormsAuthentication is a sub that actually starts the authentication:

Protected Sub doFormsAuthentication(ByVal username As String, _
                                    ByVal userData As String)
        Dim authTicket As FormsAuthenticationTicket
        authTicket = New FormsAuthenticationTicket(1, username, DateTime.Now, _
                                DateTime.Now.AddMinutes(15), False, userData)
        Dim eTicket As String = FormsAuthentication.Encrypt(authTicket)
        Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, eTicket)
        HttpContext.Current.Response.Cookies.Add(cookie)
    End Sub

You are done!

Jeffrey:
Related Post