Forms Authentication in Asp.net
Introduction:
Security is one of the most important component of any
application. Security is even more important when you are making a web
application which is exposed to million of users. Asp.net provides classes and
methods that ensure that the application is secure from outside attacks. In this
article we will investigate the Forms authentication in Asp.net which provides a
powerful way of securing applications.
Setting the forums authentication
First you need to set up the forms authentication in the
web.config file. If you see in the web.config file there will be a tag like
this:
<authentication
mode="Windows"
/>
By default it is set to the Windows authentication mode in order
to change this to forms authentication you will just need to change the windows
to forms as I have shown below:
<authentication
mode="Formss"
/>
Okay so now you have set your application to use the features of
the forms authentication instead of the windows authentication.
Storing username and password in the Web.config file:
If you have very few users that needs to use the application than you can set
the username and passwords in the web.config file.
|
<authentication
mode="Forms">
<forms
loginUrl="Login.aspx">
<credentials>
<user
name="Joe"
password="Smith"
/>
</credentials>
</forms>
</authentication>
|
You will see some new tags and attributes above lets explain all of them:
The tag forms has an attribute loginUrl which is the url of the page the
users will be redirected if they try to access an authorized page. In this case
we have given the url as Login.aspx which means that if some user is
trying to access some page and he is not signed in he will be redirected to the
Login.aspx page.
Later we have the credentials tag which has attributes username and password.
The username and password is simply the username and password for a particular
user. All the usernames and passwords that are present in the web.config files
<credentials> tag will be authorized to user the pages.
You can have multiple user name and password stored in a single web.config
file. As you can see in the code below I have stored 2 username and their
passwords:
|
<authentication
mode="Forms">
<forms
loginUrl="Login.aspx">
<credentials>
<user
name="Joe"
password="Smith"
/>
<user
name="azam"
password="hello"
/>
</credentials>
</forms>
</authentication>
|
Okay so now you got the username and passwords stored in the web.config file
and now you want to authenticate the user depending on the credentials present
in the web.config file. Let's set one more thing up which is the authorization
tags in the web.config file.
|
<authorization>
<deny
users="?"
/>
</authorization>
|
The deny users = "?" means that all the other users whose name is not present
in the web.config file must not be able to access the pages.
Lets make a simple login screen that lets the user enter his credentials:

Suppose you are too lazy to change your page name from WebForm1 to Login.aspx.
Now if you run the page you will see an error that there is no Login.aspx page.
You will be surprised that what is asp.net looking for Login.aspx page. The
reason is that because you told the Asp.net that the login page will be named
Login.aspx remember:
|
<forms
loginUrl="Login.aspx">
|
Now if you change the name of your page to Login.aspx it will work fine. You
can also change the loginUrl = WebForm1.aspx to make it work but making a
Login.aspx page sounds much better.
Now we need to implement the button click code:
|
private
void Button1_Click(object
sender, System.EventArgs e)
{
if(FormsAuthentication.Authenticate(txtUserName.Text,txtPassword.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,false);
}
else
{
Label3.Text = "you are not authorized to view the page";
}
}
|
We simply used the FormsAuthentication.Authenticate() method and supplied it
with the username and password. These username and password will be checked
against the web.config file. If the username and password are present inside the
web.config file than the user will be authorized and will be taken to the
originally requested Url. If the person is not authorized than a message will be
printed that "You are not authorized to view the page".
Cookie Expiration:
You can also expire the cookies that you make in your application. Setting
the time for the cookie expiration is not difficult at all. Lets see the
following code and see what it does:
Lets first make a simple cookie that will hold the user's username and than
set its expiration time in days:
|
HttpCookie myCookie = new HttpCookie("UserName");
myCookie.Value("UserName") =
txtName.Text;
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
|
As we can see in the code sample above that making and setting the expiration
time for the cookie is not difficult at all. You can also use
FormsAuthentication Ticket to assign the expiration time of the cookie.
This method is good if you dont want the user to be logged on all the times.
Its also safe from the security point of view cause it will expire in 1 day.
Database Authentication:
If you have a larger system you will be better off using the Database to keep
the UserNames and passwords. You can use a simple SQL Stored procedure which
returns 1 or 0 for success and failure depending on the username and password
supplied. A simple database validation method can be written as follows:
|
private
bool
IsUserAuthenticated(string
username,string
password)
{
// Make database connection
// Attach the parameters, should
also have output parameters to return a value
// set up the Sql Server Stored
procedure
/*
*
* CREATE PROC [GetUserID]
* @PersonID int OUTPUT,
* @UserName nvarchar(50),
* @Password nvarchar(50)
*
* AS
*
* SELECT @PersonID = PersonID WHERE UserName =
@UserName AND Password =
@Password;
*
*/
// exeucte the command
// if(personID > 0 )
// return true;
// else
// return false;
}
|
Signing out a user Securely:
You have seen the sign out button on the Internet on various websites.
Our site www.codersource.net also have
the feature to signout users when they are done browsing. Let's see how we can
implement a simple signout method. The logic behing the sign out is to expire
the user cookie.
|
FormsAuthentication.SignOut();
Response.Cookies["UserName"].Value =
null;
// The date can be anything which has
already passed
Response.Cookies["UserName"].Expires =
new System.DateTime(1999,10,12);
Response.Redirect("Whateverpage.aspx");
|
As you can see the code above is pretty simple and straight forward. The
FormsAuthentication class provides a signout method which can be used to signout
users.
Later we assign null to the cookie and expired the cookies date by assigning
it a date which has already passed. After signout the user I simply redirected
the user to another page.
Client side Validation
Don't leave all the things for your business logic and then for the database
to decide. Do all the validation before you send the data to the business layers
and the database layers. For this you can always use RequiredFieldValidators to
check that if the required fields are not left blank.
I hope you enjoyed the tutorial.
Happy Coding !