What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5472 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Forms Authentication in ASP.NET with C#: Advance

Forms Authentication in ASP.NET with C#: Advance

6 vote(s)
Rating: 4.67 out of 5
Article posted by Raja on 9/20/2008 | Views: 188969 | Category: ASP.NET | Level: Advance red flag


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

Download


 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

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: Avicool08 | Posted on: 01 Oct 2008 12:20:55 AM

Thank you Raja,
this article is very help full for me....and also very informative also ....thanks again...

Posted by: Dilu | Posted on: 09 Oct 2008 05:56:35 AM

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 | Posted on: 16 Oct 2008 10:47:20 AM

No, I am just encrypting the cookie using standard method provided in FormAuthenticatio class.

Thanks.

Posted by: Nav234 | Posted on: 15 Jul 2010 09:46:28 AM

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 | Posted on: 15 Sep 2010 11:43:13 PM | Points: 10

hi..your article is very nice...it is very helpful for me and provide useful information...thanks

Posted by: Navalemanoj0405 | Posted on: 03 Jan 2011 05:24:02 AM | Points: 25

Nice

Posted by: Magomes | Posted on: 02 Mar 2011 10:23:10 PM | Points: 25

Have problema in Cannot use a leading .. to exit above the top directory.
wath this...

thanks

Posted by: Praveen7k | Posted on: 01 Aug 2011 11:14:42 PM | 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 | Posted on: 19 Oct 2011 01:33:06 PM | Points: 25

Thank You very much for your article. Its really helpful.

Posted by: Aashwinjain | Posted on: 06 Nov 2011 05:24:25 PM | 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 | Posted on: 19 Jul 2012 04:41:37 AM | Points: 25

Great article...Thanks :)

Posted by: Jflundy | Posted on: 02 Nov 2012 12:11:07 AM | Points: 25

Nice coding, easy to understand and easy to implement, your a genius!

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

This article first starts with the basic concepts of CAS like evidence, permission, code groups and caspol.exe. It then moves ahead to demonstrate how CAS can be implemented in real world. This article further talks about ground up changes made in .NET 4.0 for CAS. In those regards it discusses about security transparent model and sandboxing.

In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.

.NET framework offers multiple options for achieving the development tasks and it is always challenging to decide when to use what. The data repeater controls in .NET i.e. Repeater, User Control, Custom control, dropdown list etc offers functionality of repeating the data on pages and we would discuss about those controls and their usage.

This article shows how to log error using asp.net in either a log file or in System event log.

Security is one of the major aspects in terms of a web application. Security can be implemented using different methods in a web application. One of the main components, which required high security, is the configuration files, where we will define the configurations. In this document, we will discuss about the simple way to protect the web.config entries.

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 find 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/22/2013 5:07:19 AM