Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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.

Background

ASP.NET provides four types of Authentications:

Windows (Default)

Forms

Passport

None

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"/> 
  </credentials> 
</forms> 
</authentication> 
  <authorization> 
  <allow users="*"/> 
</authorization>

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.

<authorization>
        <deny users="?"/>
</authorization>

Important

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.

Implementation

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;
        con.Open();
        dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            FormsAuthentication.RedirectFromLoginPage(txtUname.Text, false);
        }
        else
        {
            lblErrorMsg.Text = "Invalid Login!";
            lblErrorMsg.ForeColor = System.Drawing.Color.Red;
            txtUname.Focus();
        }
     }
}     

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:

"http://localhost/MyAuthentication/SecurePages/MyHome.aspx"

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.

Conclusion

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

License

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

Share

About the Author

Kamal Singh Kharayat
Technical Lead Government of Dubai
United Arab Emirates United Arab Emirates
Hi, I own Bachelor and Master in Computer Application. As a habit of learning I always use to learn new technologies. I own keen interest in self learning, specially in Microsoft .net technologies. In sports, I like to play Soccer. I own 6 year of Software Development experience in .net technologies and including 3 year in WSS and MOSS 2007.
Also I own experience of more than 1 years as a Technical Trainer for .net technologies in various IT Companies.
Currently I am working an independent IT Consultant.
We are open for assignments in SharePoint & Microsoft .NET technologies. Contact us for SharePoint Corporate Training.
 
"Improvement is the only thing which makes me happy...."
e-mail Addresses: kamalkharayat@gmail.com
skype id: stek_ks
http://kamalsinghtechriders.blogspot.com/
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionVery Helpful Sir PinmemberRavi_Patel23-May-13 3:28 
GeneralMy vote of 5 Pinmemberharishkiet118-Nov-11 7:55 
GeneralThank alot Pinmemberlemycanh22-Feb-09 5:31 
GeneralThank You Very Much ! ! ! PinmemberDomingo M. Asuncion27-Dec-07 0:32 
GeneralRe: Thank You Very Much ! ! ! PinmemberKamal Singh D. Kharayat27-Dec-07 17:12 
Thanks buddy.....
I am unable to organise the article and the page width is too high. There are some junk character getting displayed on the code. I am sorry for the inconvenience and would soon do the needful. Smile | :)
 
Kamal Singh
(Senior Software Engineer)

GeneralGood explanation about Authentication... Pinmembernishantsagar8317-Aug-07 22:41 
GeneralRe: Good explanation about Authentication... PinmemberKamal Singh D. Kharayat27-Dec-07 17:13 
GeneralSQL Injection. Pinmemberguyinfun17-Aug-07 3:11 
GeneralRe: SQL Injection. [modified] PinmemberKamal Singh D. Kharayat17-Aug-07 3:23 
GeneralGood I like this one...... PinmemberHansatSuthar16-Aug-07 23:04 
GeneralRe: Good I like this one...... PinmemberKamal Singh D. Kharayat27-Dec-07 17:13 

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

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

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