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