Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

16
Role based Role based Security in .NET Security in .NET By By Aasia Riasat Aasia Riasat CS-795 CS-795

Transcript of Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Page 1: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Role based Role based Security in .NETSecurity in .NET

ByBy

Aasia RiasatAasia Riasat

CS-795 CS-795

Page 2: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Role based Security in .NETRole based Security in .NET Use Use Forms authenticationForms authentication to obtain and validate to obtain and validate

user credentials. user credentials.

Create Forms Authentication Ticket objects based on Create Forms Authentication Ticket objects based on name and roles retrieved from the data store. name and roles retrieved from the data store.

Use Use Generic Principle classGeneric Principle class that provides the Role- that provides the Role-based authorization checking functionality. ASP.NET based authorization checking functionality. ASP.NET requires it to be stored in the HttpContext.User to relate requires it to be stored in the HttpContext.User to relate it current application Http request. it current application Http request.

Use these objects to make authorization decisions.Use these objects to make authorization decisions.

Page 3: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Role based Security in .NETRole based Security in .NET ..NET Framework provides support for the implementation of role NET Framework provides support for the implementation of role

based security which consists of Authentication (Identity) and based security which consists of Authentication (Identity) and Authorization(Rights).Authorization(Rights).

The .NET provides access to the user through an identity and The .NET provides access to the user through an identity and authorization access by principal object. authorization access by principal object.

Identities corresponds to users and their properties.Identity classes Identities corresponds to users and their properties.Identity classes belong to System.Security.Principal Namespace.belong to System.Security.Principal Namespace.

Roles are String of role names added to a Principal to associate the Roles are String of role names added to a Principal to associate the current user with his assigned roles.current user with his assigned roles.

Principal object is a collection of information about identity and roles Principal object is a collection of information about identity and roles that the current user is associated with. The that the current user is associated with. The System.Security.Principal NamespaceSystem.Security.Principal Namespace contains two classes contains two classes GenericPrincipalGenericPrincipal and and WindowsPrincipalWindowsPrincipal that are used to determine that are used to determine the properties of a principal object. .NET uses the Principal object to the properties of a principal object. .NET uses the Principal object to gain information about the identity and roles of a user.gain information about the identity and roles of a user.

Page 4: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Role base Security in .NETRole base Security in .NET

Create a Web Application with a Logon Page. Create a Web Application with a Logon Page.

Configure the Web Application for Forms Configure the Web Application for Forms Authentication.Authentication.

Generate a Generate a Authentication TicketAuthentication Ticket for for Authenticated Users.Authenticated Users.

Construct Construct Generic Principal and Forms IdentityGeneric Principal and Forms Identity Objects.Objects.

Use these objects to implement Use these objects to implement Role base securityRole base security..

Page 5: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Creating web application with Creating web application with Login PageLogin Page

Create a new ASP.NET Web Application called Create a new ASP.NET Web Application called RoleBasedSecurity.RoleBasedSecurity.

Rename WebForm1.aspx to Logon.aspx. Rename WebForm1.aspx to Logon.aspx.

Add controls to Logon.aspx to create a logon form. Add controls to Logon.aspx to create a logon form.

Set the “Text Mode” property of the password Text Box Set the “Text Mode” property of the password Text Box control to Password.control to Password.

In Solution Explorer, right-click “RoleBasedSecurity” and In Solution Explorer, right-click “RoleBasedSecurity” and click Add a Web Form.click Add a Web Form.

Enter Default.aspx as the new form's name. Set it as a Enter Default.aspx as the new form's name. Set it as a start up page.start up page.

Page 6: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Creating a web application Creating a web application with Login Pagewith Login Page

Page 7: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Application’s Web.Config fileApplication’s Web.Config file

<<authenticationauthentication modemode="Forms"> ="Forms"> <<formsforms loginUrlloginUrl="logon.aspx"="logon.aspx" namename="authCookie"="authCookie" timeouttimeout="60"="60" pathpath="/">="/"> </</formsforms>> </</authenticationauthentication>>------------------------------------------------------------------------------------------------ <<authorizationauthorization>> <<denydeny usersusers="?"="?" />/> <<allowallow usersusers="*"="*" />/></</authorizationauthorization>>

Page 8: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Generate Authentication Ticket for Generate Authentication Ticket for Authenticated UsersAuthenticated Users

The authentication ticket is a type of cookie The authentication ticket is a type of cookie used by the ASP.NET “used by the ASP.NET “Forms Authentication Forms Authentication ModuleModule” (” (System.Web.SecuritySystem.Web.Security) namespace. ) namespace.

Add “using System.Web.Security” namespace to Add “using System.Web.Security” namespace to the login.aspx webform1 class.the login.aspx webform1 class.

Add the following private method to the Add the following private method to the login.aspx’s WebForm1 class called IsAuthenticated login.aspx’s WebForm1 class called IsAuthenticated and GetRoles. These methods will be used in and GetRoles. These methods will be used in authenticating the user and getting his identity and authenticating the user and getting his identity and roles. roles.

Page 9: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Generate Authentication Ticket for Generate Authentication Ticket for Authenticated UsersAuthenticated Users

private bool IsAuthenticated( string username, string password )private bool IsAuthenticated( string username, string password ) {{ // This code would typically validate the user name and password// This code would typically validate the user name and password // combination against SQL or some other database and return true// combination against SQL or some other database and return true // or false based on the credentials found in the database.// or false based on the credentials found in the database. return true;return true;}}

private string GetRoles( string username, string password )private string GetRoles( string username, string password ) {{ // GetRoles method get the role list from database, and returns// GetRoles method get the role list from database, and returns //A pipe delimited string containing roles. This format is //A pipe delimited string containing roles. This format is //Convenient for storing roles in authentication ticket//Convenient for storing roles in authentication ticket return "Senior Manager|Manager|Employee";return "Senior Manager|Manager|Employee"; }}

Page 10: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Generating Authentication Ticket for UsersGenerating Authentication Ticket for Usersprivate void btnLogon_Click(object sender, System.EventArgs e) { bool isAuthenticated = IsAuthenticated( txtUserName.Text,txtPassword.Text );

if (isAuthenticated = = true ) { string roles = GetRoles( txtUserName.Text, txtPassword.Text ); // Create the authentication ticket FormsAuthenticationTicketauthTicket= newFormsAuthenticationTicket(1,txtUserName.Text,DateTime.Now,DateTime.Now.AddMinutes(60),false,roles ); // Encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,

encryptedTicket);

// Add the cookie to the outgoing cookies collection returned to the user’s browser Response.Cookies.Add(authCookie);

// Redirect the user to the originally requested page Response.Redirect( FormsAuthentication.GetRedirectUrl(txtUserName.Text,false) } }

Page 11: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Creating GenericPrincipal & Creating GenericPrincipal & FormsIdentity objectsFormsIdentity objects

Implement Implement Application AuthenticateRequest Application AuthenticateRequest event handler in event handler in Global.asax file.Global.asax file.

Add the following using statements to the top of Add the following using statements to the top of the Global.asax file:the Global.asax file: using System.Web.Security;using System.Web.Security; using System.Security.Principal;using System.Security.Principal;

Create Create GenericPrincipal and FormsIdentityGenericPrincipal and FormsIdentity objects based on information contained within the objects based on information contained within the authentication ticket. authentication ticket.

Page 12: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

GenericPrincipal & FormsIdentity objectsGenericPrincipal & FormsIdentity objects protectedprotected voidvoid Application_AuthenticateRequest(Object sender,EventArgs e) Application_AuthenticateRequest(Object sender,EventArgs e) {{ // Extract the forms authentication cookie// Extract the forms authentication cookie stringstring cookieName = FormsAuthentication.FormsCookieName; cookieName = FormsAuthentication.FormsCookieName;

HttpCookie authCookie = Context.Request.Cookies[cookieName];HttpCookie authCookie = Context.Request.Cookies[cookieName]; ifif((nullnull == authCookie) == authCookie) {{ return; return; // There is no authentication cookie.// There is no authentication cookie. } } FormsAuthenticationTicket authTicket = FormsAuthenticationTicket authTicket = nullnull;; trytry { { authTicket = FormsAuthentication.Decrypt(authCookie.Value);authTicket = FormsAuthentication.Decrypt(authCookie.Value); }} catchcatch(Exception ex)(Exception ex) { { return; return; // Log exception details (omitted for simplicity)// Log exception details (omitted for simplicity) }} ifif(authTicket == null)(authTicket == null) {{ return;return; // Cookie failed to decrypt.// Cookie failed to decrypt. }} // Ticket contains pipe delimited string of role names.// Ticket contains pipe delimited string of role names. stringstring[] roles = authTicket.UserData.Split([] roles = authTicket.UserData.Split(newnew charchar[]{'|'}); []{'|'}); FormsIdentity id = FormsIdentity id = newnew FormsIdentity( authTicket ); FormsIdentity( authTicket ); // Create an Identity object// Create an Identity object // This principal will flow throughout the request.// This principal will flow throughout the request. GenericPrincipal principal = GenericPrincipal principal = newnew GenericPrincipal(id, roles); GenericPrincipal(id, roles); Context.User = principal; Context.User = principal; // Attach the principal object to the current HttpContext object// Attach the principal object to the current HttpContext object }}

Page 13: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Testing the applicationTesting the application

Add code to Default.aspx file to display information from the Principal object attached to the current HttpContext object.

Confirm that the object has been correctly constructed and assigned to the current Web request.

Tests the role-based functionality supported by the Generic Principle class.

Add following using statement beneath the existing using statements. using System.Security.Principal;

Page 14: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Testing the application (Coding Testing the application (Coding Default.aspx)Default.aspx)

privateprivate voidvoid Page_Load( Page_Load(objectobject sender, System.EventArgs e) sender, System.EventArgs e){{ IPrincipal p = HttpContext.Current.User;IPrincipal p = HttpContext.Current.User; Response.Write( "Authenticated Identity is: " + p.Identity.Name );Response.Write( "Authenticated Identity is: " + p.Identity.Name ); Response.Write( "<p>" );Response.Write( "<p>" ); ifif ( p.IsInRole("Senior Manager") ) ( p.IsInRole("Senior Manager") ) Response.Write( "User is in Senior Manager role<p>" );Response.Write( "User is in Senior Manager role<p>" ); elseelse Response.Write( "User is not in Senior Manager role<p>" );Response.Write( "User is not in Senior Manager role<p>" ); ifif ( p.IsInRole("Manager") ) ( p.IsInRole("Manager") ) Response.Write( "User is in Manager role<p>" );Response.Write( "User is in Manager role<p>" ); eelselse Response.Write( "User is not in Manager role<p>" );Response.Write( "User is not in Manager role<p>" ); ifif ( p.IsInRole("Employee") ) ( p.IsInRole("Employee") ) Response.Write( "User is in Employee role<p>" );Response.Write( "User is in Employee role<p>" ); elseelse Response.Write( "User is not in Employee role<p>" ); Response.Write( "User is not in Employee role<p>" ); ifif ( p.IsInRole("Sales") ) ( p.IsInRole("Sales") ) Response.Write( "User is in Sales role<p>" );Response.Write( "User is in Sales role<p>" ); elseelse Response.Write( "User is not in Sales role<p>" );Response.Write( "User is not in Sales role<p>" ); }}

Page 15: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

Testing the applicationTesting the application

Page 16: Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.

RefrencesRefrences

http://msdn.microsoft.com/library/http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secmod/default.asp?url=/library/en-us/secmod/html/secmod08.asphtml/secmod08.asp

http://www.codeguru.com/Csharp/.NET/nethttp://www.codeguru.com/Csharp/.NET/net_security/authentication/article.php_security/authentication/article.php

http://msdn.microsoft.com/library/http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secmod/default.asp?url=/library/en-us/secmod/html/secmod20.asphtml/secmod20.asp