Documente Academic
Documente Profesional
Documente Cultură
Beginner |
Become a Sponsor
This article describe how to use Forms Authentication in ASP.NET with C#. After reading this
article you will be able to create a web application with Forms Authentication. This article also
includes downloadable sample project with source code.
Download
Download source code for Forms Authentication in ASP.NET with C#: Basic
Introduction
Forms Authentication is a mechanism to allow only authenticated user with valid credential
to view a particular page or group of pages/folders and stop unauthenticated or anonymus use
outside the secure boundry. Forms authentication uses an authentication ticket that is created
when a user logs on to a site, and then it tracks the user throughout the site. The forms
authentication ticket is usually contained inside a cookie. However, cookieless forms
authentication is also possible that works by passing user ticket in query strings.
This article describe how to create a simple Forms Authentication website with Default, Secure
and Login page. I am going to explain in easy to follow steps.
Step - 1 - Create Login page
Create a new website in Visual Studio or Visual Web Developer by going through File > New
Web Site ... Right click Solution Explorer and add a new page called Default.aspx and change its
title to Home Page. Now again add one more page called Login.aspx and drag Login control
from the toolbar (under Login section). Your page should look like below (Picture - 1)
Picture - 1
Don't worry about Home Page | Secure Page link and other text now (I have created a user
control and used that user control into my master page so that it displays in all pages that will use
my master page). Also ignores the formatting as it is appearing in the picture, however you can
select any formatting using Smart tag of the Login control. As long as User Name, Password,
CheckBox and Login button is displaying for you that is fine.
For the exact look and feel of your Login control you can copy-paste following code.
ForeColor="White" />
</asp:Login>
Double click Login control and you should see the code behind file of the Login.aspx page.
Notice that Login1_Authenticate event will be automatically created (If it has not been created
for any reason just copy-paste following code and go to the Source view of the Login.aspx and
add onauthenticate="Login1_Authenticate" attribute in the Login control .
Namespace to use
System.Web.Security;
/// <summary>
/// </summary>
if (authenticated)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
/// <summary>
/// </summary>
/// <returns></returns>
// in real scenario you should call your object and validate username and
password againt the database or whichever data source you are using
return true;
else
{
return false;
Now modify your web.config file. Just add Authentication and Authorization tag inside
<system.web> like following.
<authentication mode="Forms">
</authentication>
<authorization>
</authorization>
Let me explain in brief what are different attributes of <forms> tag are.
defaultUrl is the name of the page where user will be redirected by default after they are logging
in from home page or not secured page.
loginUrl is is the name of the page where user will be redirected when they will try to enter into
secure page/folders of the website.
slidingExpiration is the attribute that defines whether you want users session to slide if they are
continuing their work on secure page.
timeout value defines duration (in minutes) of the user session after that user session will expire
(If slidingExpiration is false otherwise timeout is count after last hit of user to the website).
Step - 3 - Create a Secure folder
Right click your website in Solution explorer and add a folder named Secure. Add a .aspx page
and name it like SecurePage.aspx. Again Add a web.config file inside it and write following
code into it inside <system.web> tag.
<authorization>
<deny users="?"/>
</authorization>
The deny tag inside authorizaton tag is specifying that this (Secure) folder is denied for all
anonymus user and only validated user should be able to access any content of this folder.
Step - 4 - Run your application
Right click your SecurePage.aspx under Secure folder and select Set As Start Page. Run your
application and you should see your browser something like above picture (Picture - 1). You can
notice that instead of directly going to SecurePage.aspx, you have been redirected to Login.aspx.
This is because you are not authenticated yet and you have specified Secure folder as the folder
where anonymus users are not allowed. Enter username and password (in my case it is "user"
and "password"), click Login button and you will be redirected to SecurePage.aspx. Try entering
wrong username and password and you will see a message something like "Your login
attempt ...".
So you are secure now :). Download the attachment of this article and you can see full
implementation of Forms Authentication described in this article along with usage of
LoginView, LoginStatus and LoginName controls.
Enjoy !!!
In VS 2005 its very simple to design a Login Page. Because there is no need
of bringing textboxes, labels & buttons together to design a login page and
writing code in that button click event. The VS 2005 have a readymade tool
in its toolbox called as “Login”.
You just have to Drag & Drop that on your .aspx page
After drag & drop you can change that to your desired design by clicking on
Auto Format
Then we need to go to the ‘Properties’ of that Login Control and click on
Events.
There we can see a event called Authenticate, Double click on it.
Once that is done. You have to write the C# code in that event
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;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
try
{
string uname = Login1.UserName.Trim(); //Get the username from the control
string password = Login1.Password.Trim(); //get the Password from the control
bool flag = AuthenticateUser(uname, password);
if (flag == true)
{
e.Authenticated = true;
Login1.DestinationPageUrl = “After_Login.aspx”;
}
else
e.Authenticated = false;
}
catch (Exception)
{
e.Authenticated = false;
}
}
if (userDS != null)
{
if(userDS.Tables[0].Rows.Count > 0)
bflag = true;
}
return bflag;
}
}