Tuesday, October 22, 2013

forms authentication in asp.net

Introduction
In this article, I am going to explain how to Role based security using Forms Authentication.

forms authentication in asp.net
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.
forms authentication in asp.net
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 !!!


Source: http://dotnetfunda.com/articles/show/141/forms-authentication-in-aspnet-with-csharp-advance

No comments:

Post a Comment