Click here to Skip to main content
13,457,717 members
Click here to Skip to main content
Add your own
alternative version


31 bookmarked
Posted 16 Aug 2007

Forms Authentication ! An Introduction

, 18 May 2008
Rate this:
Please Sign up or sign in to vote.
An Introduction to Forms Authentication and Its practical usage.


This article is intended to the beginners of Authentication and Authorization in ASP.NET. Here I tried to show how to use Forms Authentication and the related authorization, using which I can deny unauthorized access to my Secure Pages.


ASP.NET provides four types of Authentications:

Windows (Default)




Here I am interested to explore Forms Authentication.

Points of Interest

Before starting I would like to explain about Authentication and Authorization.

Authentication is a mechanism which identifies a user. Identifying a user is known as Authentication; whether you are storing User credentials in a database or configuration or may be in Active Directory of the domain.

Authorization on the other hand explains that "Which user can access a particular resource." So, in some cases it may happen that, the user is authenticated but still unable to access a resource.

Let's make it clearer with a practical problem. Suppose you are in a situation where you have to develop a web application in which five web pages are there. Among those two web pages (Login and User Registration) should be accessible to all users (Anonymous as well, so that they can register their self and login their account). Other three pages are accessible to only authenticated and authorized users. So the Login Page will authenticate the user and if the user is authenticated and authorized to view secure pages then only he/she will be redirected there. So let's see how Forms Authentication will make this possible.(Here I will take only two pages; one for login, and other which will be the home page of the user after login).

Start your Studio 2005; create a new web site named "MyAuthentication". Rename the "Default.aspx" page to Login.aspx. Now at the application name on the solution explorer and add a Web Configuration File. In web.config file by default you will find the following code in Authentication tag.

<authentication mode="Windows" /> 

Now remove this code by the following:

<authentication mode="Forms"> 
 <forms loginUrl="Login.aspx" defaultUrl="./SecurePages/MyHome.aspx" path="/" 

 protection="All" timeout="20"> 
    <credentials passwordFormat="Clear"> 
       <user name="kittu" password="tannu"/> 
       <user name="kamal.singh" password="kharayat"/> 
  <allow users="*"/> 

We changed the authentication mode to "Forms"; it means that a Form will authenticate the users. Now the <forms> tag takes lots of parameters, but we are interested in loginurl, path, and protection. Loginurl is the page where user will be redirected if he/she tries to access a secured page. If the user is authenticated and authorized for that resource, then he/she will be redirected to the desired page. DefaultUrl will the URL where the user is redirected if he/she doesn't request a particular page and logs in. Path will specify where in the hierarchy the Login page resides.

Inside forms tag you can write credentials tag if you want to store user credentials in web.config file. Frankly saying it's not practical to store credentials in configuration files. So let's store it in a database table, for this you need not to write credentials tag.

Now you must aware that this configuration file is at the root of the application and will affect all the objects at the root. Our Login Page is also at the root of the hierarchy, and we want everyone to access this login page. For this in the authorization section we have to allow everyone as done above.

Now create a folder named "SecurePages" and Put a page "MyHome.aspx" in it. This page should be displayed only when the user logs in successfully. To secure this page put a web.config file inside it. And write the following code in the authorization section of web.config file.

        <deny users="?"/>


Let me tell you, every web.config file overwrites the setting of the web.config file above it in the hierarchy. So whatever settings we will overwrite will be applicable to current directory i.e., "SecurePages". Like here we are overwriting the authorization for this directory. But remember one thing, you cannot authenticate user again and again in every web.config file. Ya…. But you can authorize the users again and again for different resources.


So, now your MyHome.aspx will not be directly accessible to every user as we have denied the anonymous users from accessing this resource. When any user will try to access the resource in side "Secure Pages", he/she will be redirected to Login page, and if the user is valid, then he/she will get the access.

Now see the code that is required on the Login button click:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 


    protected void Page_Load(object sender, EventArgs e)



    protected void btnSubmit_Click(object sender, EventArgs e)


      SqlConnection con = new SqlConnection("Data Source=ServerName; 
      Initial Catalog=MyTesting; Integrated Security=true;");

      SqlCommand cmd = new SqlCommand();

      cmd.Parameters.AddWithValue("@UserName", txtUname.Text.Trim());

      cmd.Parameters.AddWithValue("@Password", txtPword.Text.Trim());

      cmd.CommandText = "Select * from Login where UserID=@UserName and   Password=@Password";
       cmd.Connection = con;
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        if (dr.Read())
            FormsAuthentication.RedirectFromLoginPage(txtUname.Text, false);
            lblErrorMsg.Text = "Invalid Login!";
            lblErrorMsg.ForeColor = System.Drawing.Color.Red;

You can see we are verifying the credentials form database but now it's supported by Forms Authentication. See FormsAuthentication.RedirectFromLoginPage(txtUname.Text, false); Here false means you don't want to store persistent cookie for the user. Now try to Access the MyHome.aspx Directly using the following URL:


You will be redirected to Login Page, with the following URL: http://localhost/MyAuthentication/Login.aspx?ReturnUrl=%2fMyAuthentication%fSecurePages%2fMyHome.aspx

After your successful login you will be redirected to the requested page i.e., MyHome.aspx.


So there are a lot of other options with Forms Authentication, like LogOut, Username display etc. You can download the code to see the actual implementation(Please update the connection string before executing the code on your system). This article is intended to beginners. Hope it's helpful; I will go into more details in my next article. And also hope this is useful for beginners.

Till then, Enjoy….. TC


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Kamal Singh Kharayat
Technical Lead Government of Dubai
United Arab Emirates United Arab Emirates
Thank you for visiting my profile at Code Project.

I have a proven track record of delivering excellence in working on many technically challenging project across the organizations I have had worked with. My core competencies are SharePoint Development, Administration, ASP.NET, .NET MVC, SQL Server.

Adding great values to the project and team is what I work for. I believe we should deliver the best possible solutions to the customer without compromising best practices and recommendations. Also for a better project management we need to juggle things like time, cost, risk, and quality and customer satisfaction in a successful project delivery.

Specialties: Competent technologist in the field of Microsoft .NET and SharePoint Technologies.
“A successful application development always leads to Feasibility, Reliability, Scalability and more importantly a better usability.”

Blogspot Articles: Visit my blog

"Improvement is the only thing which makes me happy...."
e-mail Addresses:
skype id: stek_ks

You may also be interested in...

Comments and Discussions

GeneralGood I like this one...... Pin
HansatSuthar16-Aug-07 23:04
memberHansatSuthar16-Aug-07 23:04 
GeneralRe: Good I like this one...... Pin
Kamal Singh D. Kharayat27-Dec-07 17:13
memberKamal Singh D. Kharayat27-Dec-07 17:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180323.1 | Last Updated 19 May 2008
Article Copyright 2007 by Kamal Singh Kharayat
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid