Forms Authentication in ASP.NET with C#: Advance

Raja
Posted by in ASP.NET category on for Advance level | Views : 337052 red flag
Rating: 4.67 out of 5  
 6 vote(s)

This article describe how to create Roles based sccurity using Forms Authentication in easy to follow steps.


 Download source code for Forms Authentication in ASP.NET with C#: Advance

Introduction

In my previous article (http://www.dotnetfunda.com/articles/article114.aspx), I described how to work with forms authentication, that was the basic description about Forms Authentication. In this article, I am going to explain how to Role based security using Forms Authentication.

For the demo purpose, I have create a xml file and stored UserName, Passwod, and Roles in xml file and I will validate the user using that xml file data. In real scenario, you can use database to store username, password and roles into the database. Please note that you should store the roles of the user as comma separated values if a user have multiple roles (eg. "Admin, User" or "User" in case of single role).

Lets see how to create Role based security using Forms Authentication in easy to follow steps. I am assuming that you already have Login page ready after going through my previous article Forms Authentication in ASP.NET with C#: Basic

Create a New Project

Create a new project, you can use Visual Web Developer or Visual studio to do that and create folder structure like below.

Notice that I have create Admin, Secure and User folder to differentiate the access based on roles of the user. In my case Admin folder will have access to only those request whose role is "Admin" and "User". User folder will have access to only those request whose role is "User" and Secure folder will have access to all users who are atleast authenticated, irrespective of what role they have. Every folder has an .aspx file showing Welcome message as shown in the 1st picture above.

Create Web.Config file setting

Add following Authentication setting into your web.config file under <system.web>.

< authentication mode = " Forms " >

< forms defaultUrl = " default.aspx " loginUrl = " ~/login.aspx " slidingExpiration = " true " timeout = " 20 " ></ forms >

</ authentication >

For every user if you want to secure a particular folder, you can place setting for them either in parent web.config file (root folder) or web.config file of that folder.

Specify Role settings for the folder in root web.config file (in this case for Admin)

< location path = " Admin " >

< system.web >

< authorization >

< allow roles = " admin " />

< deny users = " * " />

</ authorization >

</ system.web >

</ location >

Write this code outside <system.web> but under <configuration> tag in the root's web.config file. Here, I am specifying that if the path contains the name of folder Admin then only user with "admin" roles are allowed and all other users are denied.

Specify Role settings for the folder in folder specific web.config file (in this case for User)

< system.web >

< authorization >

< allow roles = " User " />

< deny users = " * " />

</ authorization >

</ system.web >

Write this code into web.config file user folder. You can specify the setting for the user in root's web.config file too, the way I have done for the Admin above. This is just another way of specifying the settings. This settings should be placed under <configuration> tag.

Specify setting for Authenticated user

< system.web >

< authorization >

< deny users = " ? " />

</ authorization >

</ system.web >

Write this code into web.config file of the Secure folder. This is specifying that all anonymus users are denied for this folder and only Authenticated users are allowed irrespective of their roles.

Authenticating Users

Assuming you have gone through my previous article mentioned above, you have a login page. Now when user clicks Login button Authenticate method fires, lets see code for that method.

protected void Login1_Authenticate( object sender, AuthenticateEventArgs e)

{

string userName = Login1.UserName;

string password = Login1.Password;

bool rememberUserName = Login1.RememberMeSet;

 

// for this demo purpose, I am storing user details into xml file

string dataPath = Server.MapPath( "~/App_Data/UserInformation.xml" );

DataSet dSet = new DataSet ();

dSet.ReadXml(dataPath);

DataRow [] rows = dSet.Tables[0].Select( " UserName = '" + userName+ "' AND Password = '" + password + "'" );

// record validated

if (rows.Length > 0)

{

// get the role now

string roles = rows[0][ "Roles" ].ToString();

// Create forms authentication ticket

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (

1, // Ticket version

userName, // Username to be associated with this ticket

DateTime .Now, // Date/time ticket was issued

DateTime .Now.AddMinutes(50), // Date and time the cookie will expire

rememberUserName, // if user has chcked rememebr me then create persistent cookie

roles, // store the user data, in this case roles of the user

FormsAuthentication .FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.

// To give more security it is suggested to hash it

string hashCookies = FormsAuthentication .Encrypt(ticket);

HttpCookie cookie = new HttpCookie ( FormsAuthentication .FormsCookieName, hashCookies); // Hashed ticket

// Add the cookie to the response, user browser

Response.Cookies.Add(cookie);

// Get the requested page from the url

string returnUrl = Request.QueryString[ "ReturnUrl" ];

// check if it exists, if not then redirect to default page

if (returnUrl == null ) returnUrl = "~/Default.aspx" ;

Response.Redirect(returnUrl);

}

else // wrong username and password

{

// do nothing, Login control will automatically show the failure message

// if you are not using Login control, show the failure message explicitely

}

}


In the above method, I have used UserInformation.xml file that contains the credentials and role information for the user. The whole code is available as download (above)

I am reding the xml file and getting all the users credential into the DataSet and using DataTable.Select method, I am filtering the record based on username and password. If I found a record then I am adding the FormsAuthentication ticket into cookie after encrypting it and redirecting to the requested url if any otherwise on the default page. Notice that I have not used FormsAuthenticate standard method FormsAuthentication.RedirectFromLoginPage method to redirect from the login page after authenticating users, as this will not set the users role into the cookie and I will not be able to validate users based on the role. To add the roles of the user into the Authentication ticket, I have used FormsAuthenticationTicket class and passed required data as parameter (Notice that roles has been passed as UserData parameter of the FormsAuthenticationTicket constructor).

Till now we have set the Forms Authentication ticket with required details even the user roles into the cookie, now how to retrive that information on every request and find that a request is coming from which role type? To do that we need to use Application_AuthenticateRequest event of the Global.asx file. See the code below.

protected void Application_AuthenticateRequest( object sender, EventArgs e)

{

// look if any security information exists for this request

if ( HttpContext .Current.User != null )

{

// see if this user is authenticated, any authenticated cookie (ticket) exists for this user

if ( HttpContext .Current.User.Identity.IsAuthenticated)

{

// see if the authentication is done using FormsAuthentication

if ( HttpContext .Current.User.Identity is FormsIdentity )

{

// Get the roles stored for this request from the ticket

// get the identity of the user

FormsIdentity identity = ( FormsIdentity ) HttpContext .Current.User.Identity;

// get the forms authetication ticket of the user

FormsAuthenticationTicket ticket = identity.Ticket;

// get the roles stored as UserData into the ticket

string [] roles = ticket.UserData.Split( ',' );

// create generic principal and assign it to the current request

HttpContext .Current.User = new System.Security.Principal. GenericPrincipal (identity, roles);

}

}

}

}

In this even, after checking if user exists, he/she is authenticated and the identy type of th user is FormsIdentity, I am getting the current Identity of the user and getting the ticket I have set at the time of Authentiacting. Once I have the authenticated ticket, I just got the UserData from the ticket and split it to get roles (remember, we had stored the roles as comma separated values). Now, we have current users roles so we can pass the roles of the current user into the GenericPrincipal object along with the current identity and assign this to the curent user object. This will enable us to use the IsInRole method to check if a particular user belongs to a particular role or not.

How to Check if user has a particular role?

To check if a user belong to a particulr role, use below code. This code will return true if the current record is coming from the user who is authenticated and has role as admin.

HttpContext .Current.User.IsInRole( "admin" )

How to check if user is authenticated?

To check if the user is authenticated or not, use below code.

HttpContext .Current.User.Identity.IsAuthenticated

To get UserName of the Authenticated User

HttpContext .Current.User.Identity.Name

 

If you have followed steps, you should test it by runnig your application. Try logging in as Admin and you will be able to access all pages (Admin, User, Secure, Home). Try logging in as User and you will be able to access User, Secure, Home but not Admin. Try logging in as Secure and you will be able to access Secure, Home but not Admin, User. Try to visit all link and you will be able to access only Home link.

Please feel free to download the sample project from above link and use it. Hope this will be usefull for readers of this website. Please let me kow if you have any feedback or comments. Thanks and happy coding !!!

Note: Originally written by Sheo Narayan

Page copy protected against web site content infringement by Copyscape

About the Author

Raja
Full Name: Raja Dutta
Member Level:
Member Status: Member
Member Since: 6/2/2008 12:47:48 AM
Country: United States
Regards, Raja, USA
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Avicool08 on: 10/1/2008
Thank you Raja,
this article is very help full for me....and also very informative also ....thanks again...
Posted by: Dilu on: 10/9/2008
Hi,
Your article is very nice. However I want to know where in the code you are making sure that user has not tempered with the cookie across multiple request. I know that you are encrypting cookies but I want to know if you are also signing them ?
Or if you have some other mechanism to make sure that user is not tempering with the cookies.

Regards,
Adeel Suleman.
Posted by: Raja on: 10/16/2008
No, I am just encrypting the cookie using standard method provided in FormAuthenticatio class.

Thanks.
Posted by: Nav234 on: 7/15/2010
Hi raja,
that was a really a nice article,but difficult for a beginner like me to understand the full code and flow.
Moreover most of the methods are user defined
(GenericPrincipal ,IsInRole) and dont know what is written inside those methods.

So is there any simpler code to authorize users with priveledges through for authentication.?

thanks in advance
Naveen...
Posted by: Jasmine on: 9/15/2010 | Points: 10
hi..your article is very nice...it is very helpful for me and provide useful information...thanks
Posted by: Navalemanoj0405 on: 1/3/2011 | Points: 25
Nice
Posted by: Magomes on: 3/2/2011 | Points: 25
Have problema in Cannot use a leading .. to exit above the top directory.
wath this...

thanks
Posted by: Praveen7k on: 8/1/2011 | Points: 25
Thanks it is very helpful for beginners like me.
i implemented the same way as you did, but it is giving the windows credentials for
HttpContext .Current.User.Identity.Name ..how to resolve this...thanks
Posted by: Jgugnani on: 10/19/2011 | Points: 25
Thank You very much for your article. Its really helpful.
Posted by: Aashwinjain on: 11/6/2011 | Points: 25
thank you very much for the article.
i hav a very urgent doubt.
how do i connect my sql datbase to the asp.net code
as in how to i place the data connection
please reply
very urgent

Posted by: Abhilashhari on: 7/19/2012 | Points: 25
Great article...Thanks :)
Posted by: Jflundy on: 11/2/2012 | Points: 25
Nice coding, easy to understand and easy to implement, your a genius!

Login to post response

Comment using Facebook(Author doesn't get notification)