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. :)

Step by step guide to fix Angular app refresh issue in IIS

If you deploy your Angular app in IIS, routing will be handled from the client. So when you refresh a page it will give you 404 error. To get ride of the above-mentioned situation we have to follow the steps as follows: Before deploying anything on IIS, you have to install the URL Rewriting module on the IIS server. Please refer the link. After the installation, you should be seeing the following icon. If you are above to deploy an Angular app when is developed with ASP.Net Core. That deployment steps are explained in my previous blog post . That blog spot explains one issue I came across when I was deploying Angular 7 App with ASP.Net Core in IIS. So now we are done with IIS side installation next, we have to check the deployment files. You have to make sure that web.config file. web.config should contain the followings: <?xml version=”1.0" encoding=”UTF-8"?> <configuration> <system.webServer> <rewrite> <rules>

Generic Repository with Entity Framework Core

Recently I worked on a project with ASP.NET Core which uses Entity Framework Core. With them, I used a generic repository pattern in the data layer. Repository interface was like below: using System; using System.Collections.Generic; using System.Linq.Expressions; using OnlineSurvey.Models; namespace OnlineSurvey.Data { public interface IRepository<T> where T : BaseEntity { T GetById(int id, params Expression<Func<T, object>>[] includExpressions); void Add(T entity); void Delete(T entity); void Delete(int id); IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includExpressions); IEnumerable<T> Find(Expression<Func<T, bool>> where); int Count(); } } And the implementation was like below: using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Collections.Generic; using Syste