Completely Free .NET word API

Resources » .NET programming » ASP.NET/Web Applications

Form Authentication – ASP.NET

Updated: Category: ASP.NET/Web Applications
Author: Member Level: GoldPoints: 10

This article is an attempt to outline the importance of Forms-based Authentication, that can be used for implementing secure web sites during designing any web application.

Hello EveryOne.. i am back again with this article ...This article is an attempt to outline the importance of Forms-based Authentication, that can be used for implementing secure web sites during designing any web application.

It has become very common requirement for various web sites to have strong login/Authentication system, particularly when web site has restriction over the contents of various pages. Authentication is the way of identifying credentials such as name and password from a user and validating them against there information.

Forms-based authentication enables applications to provide its own way to do the credential validation. By this way ASP.NET authenticates users and redirects any unauthenticated users to the specific URL or login page. In this way it also performs all the necessary cookie management. Thus Forms authentication is best used when any unauthorized requests has to be redirected to form/page, using HTTP client-side redirection. Again it is a good choice if application needs to collect its own user credentials at login time through forms and users are required to provide credentials via a form. If the application authenticates the request, the system issues a cookie that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the cookie in the request headers. The requests are authenticated and authorized by an ASP.NET event handler using whatever validation method the application specifies.

When using forms-based authentication the application needs to be configured for this type of authentication system. This is achieved by setting <authentication> to Forms, and denying access to anonymous users in the Web.config file. Following is the snapshot of Web.config file that uses form authentication.

<authentication mode="Forms"/>
<deny users="?" />

Using <Form> tag various details can be mentioned that are used by the application like name of the cookie to be used, the protection type, the URL to use for the unauthenticated users, duration for which cookie will be valid, the path to use for the issued cookie and etc. Following is the illustration of each on the properties that are used in form tag

loginUrl : This is the URL to which unauthenticated users are redirected.

Name: This is the Name of the HTTP cookie that will be use by the application for authentication purposes. When we use "/" the cookies takes the current Path value when setting authentication cookies.

Timeout: This is the amount of time after which the cookie expires. This property is specified in minutes (integer) values default value is 30. The timeout for this cookie starts ticking from the time last request was received.

Path: This is path that will be used to store the information in cookies.

Protection: Through this we can specify the way cookie data need to be protected. It take four values, ALL, NONE, Encryption, Validation

Encryption: Using this value the cookies information is kept in encrypted format. Encryption can be anyone of TripleDES or DES.

Validation: This option is used when the cookie needs to be validated for any alteration or modification of the data.

ALL: This is option is used when both data validation and encryption of is required for the cookies.

NONE: This option is used when there is very week security requirement, when both data validation and encryption is not required and cookies are used for just personalization purpose.

Here is an example using the various attributes in the form tag

<authentication mode="Forms">
<forms name=".MyApplicationCookie" loginUrl="login.aspx" protection="all" timeout="30" path="/">
<!-- protection="[All|None|Encryption|Validation]" -->

Form Authentication – ASP.NET Example:
For the sake of simplifying the explanation we will create a web control that will be used for form authentication.

Web control : LoginWebControl.ascx
This web control will have following entries

<%@ Control language="C#" %>
<script language="C#" runat="server">

public String UserId {
get {
return LoginId.Text;
set {
LoginId.Text = value;

public String Password {
get {
return UserPassword.Text;
set {
UserPassword.Text = value;

public bool IsValid {
get {
return Page.IsValid;
<table style="font: 10pt verdana;border-width:1;
cellspacing=15 ID="LoginDetailsTable">
<td><b>Login: </b></td>
<td><ASP:TextBox id="LoginId" runat="server"/></td>
<td><b>Password: </b></td>
<td><ASP:TextBox id="UserPassword" TextMode="Password"
<td><ASP:Button Text="Submit"
OnServerClick="Submit_Click" runat="server"/></td>
<td align="center" valign="top" colspan="2">
<asp:RegularExpressionValidator id="ValidatorPasswordLength"
ASPClass="RegularExpressionValidator" ControlToValidate=" UserPassword "
runat=server> Password should be more the 5 character<br>
<asp:RequiredFieldValidator id="ValidatorUser"
ControlToValidate=" LoginId "
Please enter the userid
<asp:RequiredFieldValidator id="ValidatorPassword"
ControlToValidate=" UserPassword "
Please enter the password

We need to change the configuration file to reflect the form Authentication

<customErrors mode="Off"/>
<authentication mode="Forms">
<forms name=".ASPXValidationDetails" loginUrl="login.aspx" protection="All"
timeout="30" path="/" />
<deny users="?" />

As you can see the in authentication tag the mode has been put with the value of form this indicates that this is going to be a form based authentication.

In authorization tag we deny any un-authenticated request for any of the directory or sub directory resources where the web.config is placed. This is done using <deny> tag, in any other case when there is a need to allow the resource we can use the <allow> tag.

Now lets create the login.aspx which uses the LoginWebControl.ascx web control.

<%@ Page language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Register TagPrefix="Mynamespace" TagName="Login" Src=" LoginWebControl.ascx" %>

<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs E) {
if ((Page.IsPostBack) && (Page.IsValid)) {
string strDSN =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\UsersDetails.mdb";
string strSQL = "SELECT userId, userPassword FROM UserLoginInfo
WHERE userName='" + UserLoginInfo.UserId + "'";

OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
OleDbDataReader myDr = null;
try {
myDr = myCmd.ExecuteReader();

if(myDr.Read()) {
if(myDr.GetString(1).Trim() == UserLoginInfo.Password.Trim()) {
FormsAuthentication.RedirectFromLoginPage(UserLoginInfo.UserId, false);
errorMessage.Text = "Password doesn’t match with the Userid.";
errorMessage.Text = "Userid not found.";
catch(Exception codeException) {
Response.Write("There is an exception in the code: " + codeException.Message);
finally {
User Login Screen
<form ID="loginForm" name ID="loginForm" runat="server" >
<asp:Label id="errorMessage" runat="server" />
< Mynamespace:Login id="UserLoginInfo" runat="server"/>

As you can see the FormsAuthentication.RedirectFromLoginPage(UserLoginInfo.UserId, false); is used redirect a valid and authentic user to the required page

Enjoy Programming

"Quitters Never Win and Winners never Quit"

Did you like this resource? Share it with your friends and show your love!

Responses to "Form Authentication – ASP.NET"
Author: Narasimha rao  13 Jul 2007   Member Level: Bronze   Points : 0
Hello friend , thanking for giving nice article


Post Comment:

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)

    Type the numbers and letters shown on the left.

    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India