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

Form Authentication – ASP.NET


Posted Date: 28-Apr-2006  Last Updated:   Category: ASP.NET/Web Applications    
Author: Member Level: Gold    Points: 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.



<Configuration>
<system.web>
<authentication mode="Forms"/>
<Authorization>
<deny users="?" />
</Authorization>
</system.web>
</configuration>


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]" -->
</forms>
</authentication>

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;
}
}
</script>
<table style="font: 10pt verdana;border-width:1;
border-style:solid;border-color:black;"
cellspacing=15 ID="LoginDetailsTable">
<tr>
<td><b>Login: </b></td>
<td><ASP:TextBox id="LoginId" runat="server"/></td>
</tr>
<tr>
<td><b>Password: </b></td>
<td><ASP:TextBox id="UserPassword" TextMode="Password"
runat="server"/></td>
</tr>
<tr>
<td></td>
<td><ASP:Button Text="Submit"
OnServerClick="Submit_Click" runat="server"/></td>
</tr>
<tr>
<td align="center" valign="top" colspan="2">
<asp:RegularExpressionValidator id="ValidatorPasswordLength"
ASPClass="RegularExpressionValidator" ControlToValidate=" UserPassword "
ValidationExpression="[0-9a-zA-Z]{5,}"
Display="Dynamic"
Font-Size="8pt"
runat=server> Password should be more the 5 character<br>
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator id="ValidatorUser"
ControlToValidate=" LoginId "
Font-Size="8pt"
Display="Dynamic"
runat=server>
Please enter the userid
</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="ValidatorPassword"
ControlToValidate=" UserPassword "
Font-Size="8pt"
Display="Dynamic"
runat=server>
Please enter the password
</asp:RequiredFieldValidator>
</td>
</tr>
</table>

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

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

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 {
myConn.Open();
myDr = myCmd.ExecuteReader();

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


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 2007Member Level: Bronze   Points : 0
Hello friend , thanking for giving nice article


Feedbacks      

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
    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Gopi A
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India