thefrozencoder

Programming and Technology blog

Rolling Your Own Custom Authentication For ASP.NET


Introduction

ASP.NET Membership combined with Forms authentication provides a convenient way to implement page protection and user authentication.  In some cases this you may want to create your own custom authentication implementation when specific requirements do not allow the built in authentication.  This post shows the basis and a starting point of building your own custom authentication mechanism using ASP.NET.

The code samples in this article can be downloaded using the link at the bottom of this post.  Samples were created using Visual Studio 2008 and using SQL Server 2005 Express.  There are samples for both C# and Visual Basic.NET in the download file as well as a word document version of this post.

Setup

Everything needed to run the samples should be present in the download files.  Before you run the project from VS set the Secure.aspx page as the start up page, when the site is run you should be redirected to the Login.aspx automatically.  From there you can use the login information

  • Login: user@login.net
  • Password: password

There is a setting in the web.config file to control the time in seconds it takes for a user's session to expire I have set this to a low number (5 seconds) for demonstration purposes so once you are logged in and the Secure.aspx page is displayed hit the refresh on your browser a couple of times then wait 5 seconds and do another refresh, you should be redirected to the Login.aspx page since your session has expired.

Requirements

First we will take a look at some common requirements that are typical of a authenticated web site.

  • The system must be able to deny access to all pages that are defined as being secure from anonymous users.
  • The system must be able to authenticate / validate a user before they have access to secure pages
  • Once a user has been authenticated the user will not have to enter credentials again to access secure pages
  • If the user is inactive for x minutes the system will log them out and they will have to login again
  • The logged in session for a user will only be active for the duration of the browser session or until requirement 4 has been met.

Based on our requirements we are going to need a way to store user information; specifically the login and password information.  As well we will need to store some form of a security token that the system creates after authentication and stores a copy of that token in the system as well on the user’s machine.  We store the systems copy of the token in a database and clients’ copy of the token in a cookie (this will cause issues if the client does not allow cookies but for this article that will not be addressed).  We will also need a simple way to implement our security logic for pages that need it.

System Database

Below is the system database tables to store the user information as well as a copy of the security token.

ClientData Table

  • ClientID - will store the unique identifier for the client (used internal to the system)
  • FirstName - will store the users first name
  • LastName - will store the users las name
  • Login - will store the user's login
  • Password - will the users password (tipically the users password is stored encrypted rather than plain text like in this sample)

ClientSessions Table (will store the security token for the user)

  • SessionGuid - will store the system created security token, this value must match the same token on the clients computer (cookie)
  • ClientID (optional) – will store the unique id from the ClientData table for the authenticated user (in some cases this cannot be stored as it may violate privacy laws by uniquely identifying a users session on a site)
  • SessionLastActiveDate – will store a timestamp when the last time the users session was validated
  • SessionTimeOut – will store in seconds how long since the last time the users session was validated before it will expire

User Validation

User validation takes place on the Login.aspx page when the user enters their credentials and the page is submitted.  The system will then query the ClientData table to find a match for the given login and password.  If a match is found the system then creates a security token, saves the token to both the system and the user’s machine via a cookie.  The system then redirects the user to one of the secure pages within the site.  If a match is not found the Login.aspx page displays a message to the user.

Session Validation

Session validation takes place whenever a user browses a page that is considered to be secure.  The page will ask the system if the user has validated by querying the ClientSessions table using the security token from the user’s cookie and match that token to possible existing token stored in the ClientSessions table.  If the session timeout has not expired since the last validation the session is updated with a new last active timestamp.  If the session has expired the user will be forced to the login screen.

Implementation

To implement the logic the following files have been added to an ASP.NET Web Site and shown below is the files that make up the solution

  • The SecurePage Class will implement our authentication logic and be implemented by each of the pages in our site
  • The DataHelper Class implements the data access to the system database
  • The SettingsHelper Class implements the data access to the web.config file for any configurable settings
  • The Sessions.mdf is the database where we will store our user data and the user token
  • The Login.aspx page is interface the user will use to authenticate
  • The Secure.aspx page is a page that the a user must authenticate first to view
  • The UnSecure.aspx page is a page that a user does not have to authenticate to view

SecurePage Class

Below is the implementation of the SecurePage class which all of pages in our site will implement.

  • Line 15 – implements the call made by secure pages to check if the user has been validated by the system to see the current page
  • Line 28 – implements the call made by the Login.aspx page to validate the user against the data in the ClientData table
  • Line 47 – implements an internal call to get the security token from the user’s machine (cookie)

Login.aspx Page UI

The basic login page UI

Login.aspx Page Code Behind

  • Line 8 – The Login page class implements the SecurePage class to implement the methods for our authentication
  • Line 10 - The login button click when the user clicks on the login button the page calls the Login method passing in the values from the login and password text boxes.  If successful the page redirects to a secure page if not displays the user error message

Secure.aspx Code Behind

  • Line 8 – The Secure page class implements the SecurePage class to implement the methods for our authentication
  • Line 10 – The OnPreInit method is overridden so we can call the IsClientValidated method to check if the user has been validated to see the secure page.  If the user has not been validated it redirects to the Login.aspx page otherwise the Secure.aspx page displays as normal

Conclusion

There are other things to consider that are beyond the scope of this article such as using SSL for the login and or secure pages, encrypting persistent data (either cookie or user data), etc.  This by no means is a complete solution but describes the basics in creating custom authentication for an ASP.NET based web site.  This may not be the holy grail of custom authentication but it does offer a few ideas and solutions to implementing your own custom authentication when the built in membership and forms authentication does not fit well with your requirements.  Now you could just have implemented the server storage in a session item and just compared the users cookie value to the session item which would work too but what if your web site is running under a web farm and load balanced?  Unless you use a state server or sql server to store your state you will need a way to persist your authentication in a more permanent or statefull way.

** Note **
The data access layer used is the Microsoft Patterns and Practices Enterprise library which can be downloaded here http://www.codeplex.com/entlib I have encluded only the required assemblies in the download file you may need to download the entire package in order for the samples to run.

Code samples CustomAuthentication.zip (1.49 mb)