Skip to main content

How To Implement Forms-Based Authentication in Your ASP.NET Application by Using C# .NET

These days I was so busy to find how to Implement form based authentication in my ASP.net application. I was looking for a resource that I can use on web. I found some and most of them are not that easy to understand. So I though to write an article so then any one can read and get the basic idea from it.

I will first explain what is my scenario. I have my own database table to keep user credentials. So I wanted to use it to authenticate the users who are trying to log in.

This has nothing more than configuring your Web.config and writing few codes authenticate the user.

If you have your own database table to keep user credential, obviously you have a method written to authenticate. We can use this method to validate user and based on the results of this method you can do the authentication part.

These are the configuration lines that you have to put in to our Web.config.
<authentication mode="Forms"> <authentication mode="Forms">
<forms loginurl="Login.aspx">
</authentication>
This part in the Web.config will help you to say that you are going to use form authentication and go to the URL in loginUrl attribute if the user not authenticated.

If you want to check this authentication part for all the pages except Login.aspx. You can simply add following part to the Web.config and it will do the job.
<authorization>
<deny users="?">
<allow users="*">
</allow></deny></authorization>
This tells to allow all users who are authenticated and will tell to deny those who are not authenticated. Simple as that.

I know what you are thinking now. What if i don't wanna check authentication for all pages. It is also simple. You have to tell Web.config that these are pages that I want to authenticate. You can ignore the Web.config part I explained you just now and this following part for each page that you want to authenticate.
<location path="Default.aspx">
<system.web>
<authorization>
<deny users="?"></deny>
</authorization>
</system.web>
</location>


So know you know what is happening here. It will not allow any unauthenticated users to access this page. Like wise you have to add this part for the all pages you want to authenticate.

Now time has come to do coding.

Choose the place that you going to authenticate your users. Think you have method called ValidateUser(string userName, string password) which returns a boolean value as result.

If you get this result as true that mean user is authenticated and it is good to go. Before we proceed to other pages we have do some stuffs to let the application know that this user has authenticated.

This can be done in 2 ways. First one will do the job through one line of code. Second will do the job with few lines of code but it give you more control than the first one.

First way:
if (ValidateUser(txtUserName.Value,txtUserPass.Value))
FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, chkPersistCookie.Checked);
else
Response.Redirect("logon.aspx", true);

Do not get confused with these names I have given. You can use your control names here.
and this chkPersistCookie.Checked part will tell whether you want to remember this user and log him/her directly without asking anything next time.

Second way:

if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);

ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;

ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect==null)
strRedirect = "default.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);

That's all. Now you are good to go. Your site if fully authenticated now.

I think you got some thing out of this. Please let me know if you want to know something more.(Comments)

Thanks.

Comments

Popular posts from this blog

Exit a T-SQL Cursor When Condition is met

Have you ever wanted to exit from a cursor when a condition is met? I wanted to do it. So this is how I did it. DECLARE @Field1 AS INT DECLARE @Field2 AS INT DECLARE CursorName CURSOR READ_ONLY FOR SELECT Field1, Field2 FROM TableName OPEN CursorName FETCH NEXT FROM CursorName INTO @Field1, @Field2 WHILE @@FETCH_STATUS = 0 BEGIN IF @Field1 = 1 BEGIN GOTO ENDCURSOR END FETCH NEXT FROM CursorName INTO @Field1, @Field2 END ENDCURSOR: CLOSE CursorName DEALLOCATE CursorName I have set my fonts to bold where you want to notice. So that's all I hope you will get something out of it and it is true that this is not a big deal. :)

How to use DataBinder.Eval in HyperLink NavigationUrl - ASP.net

I wanted to append page Url with DataBinder.Eval value in ASP.NET hyperlink control on ASP.NET HTML source. I was trying it using many ways and also search for resources on web but I could not find any useful thing. I thought this will help u guys to get an idea about appending two strings. Solution as follows. <asp:HyperLink ID="customerHyperLink" runat="server" Text= ' ' NavigateUrl=' ' ></asp:HyperLink> You can see how I have appended these two value in NavigateUrl property. Hope some one will get the advantage of this post.

Common Design Principles

There are number of common design principles that, like design patterns, best practice over the years to build maintainable software. I'm up to describe some widely used design principles though out the post. Following common principle are extracted by the same book that I mentioned before ( Professional ASP.Net Design Patterns - Scott Millet ). Principles are as follows: Keep It Simple Stupid (KISS) One common issue in software programming is over-complicating a solution. So main concern of this principle is keep the code simple but not simplistic. Eventually this will avoid unnecessary complexities. Don't Repeat yourself (DRY) Main concern of this principle is to avoid the repetition. In other words this is all about abstracting out the common functionalities into a single place. Ex: If there is a price calculation method in a system. It should lay in a single place there. Tell Don't Ask The Tell, Don’t Ask principle is closely aligned with encapsulation and the assignin...