Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 29767 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Forms Authentication in ASP.NET with C#: Basic

Forms Authentication in ASP.NET with C#: Basic

Article posted by Raja on 7/30/2008 | Views: 48092 | Category: ASP.NET | Level: Beginner red flag


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.

<asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"

BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

Font-Size="0.8em" ForeColor="#333333" onauthenticate="Login1_Authenticate">

<TextBoxStyle Font-Size="0.8em" />

<LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"

BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />

<InstructionTextStyle Font-Italic="True" ForeColor="Black" />

<TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"

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

FormsAuthentication object exists in following namespace.

System.Web.Security;

/// <summary>

/// Fires when Login button will be clicked

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

{

bool authenticated = AuthenticateMe(Login1.UserName, Login1.Password, Login1.RememberMeSet);

if (authenticated)

{

FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);

}

}

/// <summary>

/// Authenticate user

/// </summary>

/// <param name="userName"></param>

/// <param name="password"></param>

/// <param name="rememberUserName"></param>

/// <returns></returns>

private bool AuthenticateMe(string userName, string password, bool rememberUserName)

{

// just hard code the username for this demo

// in real scenario you should call your object and validate username and password againt the database or whichever data source you are using

string localUserName = "user";

string localPassword = "password";

 

 

if (userName.Equals(localUserName) && password.Equals(localPassword))

{

return true;

}

else

{

return false;

}

}





In the Login1_Authenticate event I am calling AuthenticateMe function that is validating the user for their username and password and returning true or false. For simplicity I have just hard coded username and password, in real scenario you should validate them using your datasource (database or active directory or whatever). If AuthenticateMe function returns true I am using FormsAuthentication.RedirectFromLoginPage method of FormsAuthentication object and passing username and Remember Me checkbox status (Don't get involved into it, Its simple. If checkbox will be checked user will be able to continue their session after closing and reopening their browser else not).

Step - 2 - Create Web.Config file setting

Now modify your web.config file. Just add Authentication and Authorization tag inside <system.web> like following.

<authentication mode="Forms">

<forms defaultUrl="default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="20"></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 !!!

To implement Role Based Forms Authentication See http://www.dotnetfunda.com/articles/article141.aspx

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Raja Dutta

Experience:5 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, June 02, 2008
Level:Starter
Status: [Member]
Biography:
 Responses
Posted by: Poster | Posted on: 16 Oct 2008 10:41:40 AM

Thank you Raja. This one is good. Your interview questions posted here are very useful.

Posted by: Peno | Posted on: 05 Mar 2011 12:04:05 PM | Points: 25

Nice article and working fine under Visual studio 2008.
But when I update to Visual studio 2010, I get the following error when I run the project:

Server Error in '/Learn' Application.

HTTP Error 403 - Forbidden.

What is going wrong?

Posted by: 0194ca071007 | Posted on: 05 Apr 2011 01:02:00 PM | Points: 25




ERROR in below line of code.....
********************************************************************************************************
cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;
***********************************************************************************************************8
{"An SqlParameter with ParameterName '@OutRes' is not contained by this SqlParameterCollection."}


plz help me out what the error is in the code
and when I click login button without uername/password It gives error Invalid login but when I enter user /password Ishows the above error sqlexception

somthing error in ur posted code in the this address http://www.dotnetfunda.com/articles/article114.aspx plz check and give the solution thnkz...



Posted by: Akiii | Posted on: 02 Jun 2011 02:26:09 AM | Points: 25

good article....

Thanks and Regards
Akiii

>> Write Response - Respond to this post and get points
Related Posts

Stored procedure helps to make your work easy. With the help of these you just have to supply some parameters only.

In this article, I shall show how to do common operations like Copy, Move, Delete, Create, Rename and Search files and folders in ASP.NET.

Data audit trail is one of the most required features in any project. This article will talk about audit trail through application using prototype pattern. Most the projects have three tier architecture and have the core business objects in place. In this article we will see how we can leverage the current business objects to implement auditing functionalities.

Express edition are downsized free IDE provided by Microsoft, so that developers and experiment to feel how the enterprise edition will look like. One of the products provided in the express edition suite is the web developer 2008 express edition. VS web developer edition helps us to make web application in .NET. One of the big drawbacks of VS web developer express edition is that it helps to debug but does not compile the ASPX pages. In other words no DLL is generated for the ASPX pages. This tutorial will discuss how we can use the aspnet_compiler.exe to generate DLL for web projects developed in VS 2008 web developer express edition.

In this section we will discuss how we can make plug & play architecture using policy application blocks. What we will do is we will take a practical scenario where we want to enable logging for an application depending on situations

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/28/2012 11:54:48 AM