2
Most read
3
Most read
4
Most read
Role based
Security in .NET
By
Sudhanshu kumar
Role based Security in .NET
Use Forms authentication to obtain and validate
user credentials.
Create Forms Authentication Ticket objects based
on name and roles retrieved from the data store.
Use Generic Principle class that provides the Rolebased authorization checking functionality. ASP.NET
requires it to be stored in the HttpContext.User to
relate it current application Http request.
Use these objects to make authorization decisions.
Role based Security in .NET
.NET Framework provides support for the implementation of role
based security which consists of Authentication (Identity) and
Authorization(Rights).
The .NET provides access to the user through an identity and
authorization access by principal object.
Identities corresponds to users and their properties.Identity classes
belong to System.Security.Principal Namespace.
Roles are String of role names added to a Principal to associate the
current user with his assigned roles.
Principal object is a collection of information about identity and roles
that the current user is associated with. The
System.Security.Principal Namespace contains two classes
GenericPrincipal and WindowsPrincipal that are used to determine
the properties of a principal object. .NET uses the Principal object to
gain information about the identity and roles of a user.
Role base Security in .NET
Create a Web Application with a Logon Page.
Configure the Web Application for Forms
Authentication.
Generate a Authentication Ticket for
Authenticated Users.
Construct Generic Principal and Forms Identity
Objects.
Use these objects to implement Role base security.
Creating web application with
Login Page
Create a new ASP.NET Web Application called
RoleBasedSecurity.
Rename WebForm1.aspx to Logon.aspx.
Add controls to Logon.aspx to create a logon form.
Set the “Text Mode” property of the password Text Box
control to Password.
In Solution Explorer, right-click “RoleBasedSecurity” and
click Add a Web Form.
Enter Default.aspx as the new form's name. Set it as a
start up page.
Creating a web application
with Login Page
Application’s Web.Config file
<authentication mode="Forms">
<forms loginUrl="logon.aspx"
name="authCookie"
timeout="60"
path="/">
</forms>
</authentication>
-----------------------------------------------<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Generate Authentication Ticket for
Authenticated Users
The authentication ticket is a type of cookie
used by the ASP.NET “Forms Authentication
Module” (System.Web.Security) namespace.
Add “using System.Web.Security” namespace to
the login.aspx webform1 class.
Add the following private method to the
login.aspx’s WebForm1 class called IsAuthenticated
and GetRoles. These methods will be used in
authenticating the user and getting his identity and
roles.
Generate Authentication Ticket for
Authenticated Users
private bool IsAuthenticated( string username, string password )
{
// This code would typically validate the user name and password
// combination against SQL or some other database and return true
// or false based on the credentials found in the database.
return true;
}
private string GetRoles( string username, string password )
{
// GetRoles method get the role list from database, and returns
//A pipe delimited string containing roles. This format is
//Convenient for storing roles in authentication ticket
return "Senior Manager|Manager|Employee";
}
Generating Authentication Ticket for Users
private 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)
}
}
Creating GenericPrincipal &
FormsIdentity objects
Implement Application AuthenticateRequest
event handler in Global.asax file.
Add the following using statements to the top of
the Global.asax file:
using System.Web.Security;
using System.Security.Principal;
Create GenericPrincipal and FormsIdentity
objects based on information contained within the
authentication ticket.
GenericPrincipal & FormsIdentity objects
protected void Application_AuthenticateRequest(Object sender,EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie)
{
return; // There is no authentication cookie.
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
return; // Log exception details (omitted for simplicity)
}
if(authTicket == null)
{
return;// Cookie failed to decrypt.
}
// Ticket contains pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[]{'|'});
FormsIdentity id = new FormsIdentity( authTicket ); // Create an Identity object
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal; // Attach the principal object to the current HttpContext object
}
Testing 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;
Testing the application (Coding
Default.aspx)
private void Page_Load(object sender, System.EventArgs e)
{
IPrincipal p = HttpContext.Current.User;
Response.Write( "Authenticated Identity is: " + p.Identity.Name );
Response.Write( "<p>" );
if ( p.IsInRole("Senior Manager") )
Response.Write( "User is in Senior Manager role<p>" );
else
Response.Write( "User is not in Senior Manager role<p>" );
if ( p.IsInRole("Manager") )
Response.Write( "User is in Manager role<p>" );
else
Response.Write( "User is not in Manager role<p>" );
if ( p.IsInRole("Employee") )
Response.Write( "User is in Employee role<p>" );
else
Response.Write( "User is not in Employee role<p>" );
if ( p.IsInRole("Sales") )
Response.Write( "User is in Sales role<p>" );
else
Response.Write( "User is not in Sales role<p>" );
}
Testing the application
Refrences
http://msdn.microsoft.com/library/defaul
t.asp?url=/library/enus/secmod/html/secmod08.asp

http://www.codeguru.com/Csharp/.NET/net_s
http://msdn.microsoft.com/library/defaul
t.asp?url=/library/enus/secmod/html/secmod20.asp

More Related Content

PPTX
Http request and http response
PPTX
Input Validation
PPS
Jsp chapter 1
PPT
Introduction to event driven programming
PPTX
Session bean
PDF
JavaScript - Chapter 8 - Objects
PPTX
C# Asynchronous delegates
Http request and http response
Input Validation
Jsp chapter 1
Introduction to event driven programming
Session bean
JavaScript - Chapter 8 - Objects
C# Asynchronous delegates

What's hot (20)

PDF
7 Deadlocks
PDF
Design Pattern in Software Engineering
PPTX
Common language runtime clr
PPTX
Introduction to AngularJS
PPTX
Angularjs PPT
PDF
Enterprise JavaBeans(EJB)
PPTX
Threads ppt
PPTX
ASP.NET State management
PPTX
Multithreading and concurrency in android
PPT
PHP - Introduction to PHP AJAX
PPTX
Introduction to Angularjs
PPTX
Spring mvc
PPTX
Android Architecture.pptx
PPTX
Deadlock Avoidance in Operating System
PPTX
Implicit object.pptx
PPTX
Asp.Net Core MVC with Entity Framework
PPT
Map Reduce
PPTX
1 Fundamentals of EDP (2).pptx
PPTX
Angular Components.pptx
PPTX
Demand paging
7 Deadlocks
Design Pattern in Software Engineering
Common language runtime clr
Introduction to AngularJS
Angularjs PPT
Enterprise JavaBeans(EJB)
Threads ppt
ASP.NET State management
Multithreading and concurrency in android
PHP - Introduction to PHP AJAX
Introduction to Angularjs
Spring mvc
Android Architecture.pptx
Deadlock Avoidance in Operating System
Implicit object.pptx
Asp.Net Core MVC with Entity Framework
Map Reduce
1 Fundamentals of EDP (2).pptx
Angular Components.pptx
Demand paging
Ad

Similar to Rolebased security (20)

PPT
Implementing application security using the .net framework
PDF
Spring Framework - Spring Security
PPTX
ASP.NET Lecture 5
PPTX
State management
PDF
Aspnet auth advanced_cs
PPT
Forms authentication
DOCX
Authorization in asp
PDF
Introduction to PicketLink
PPTX
Sécurisation de vos applications web à l’aide du composant Security de Symfony
PPT
Nj 09 T2 David Frischknecht
PDF
Java Web Programming [9/9] : Web Application Security
PPSX
08 asp.net session11
PPT
JavaEE Security
PPT
State management in ASP.NET
PPT
Java Cert Pki
PDF
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
PPTX
Integrating Security Roles into Microsoft Silverlight Applications
PPTX
Security: Odoo Code Hardening
PPT
2310 b 16
PPT
2310 b 16
Implementing application security using the .net framework
Spring Framework - Spring Security
ASP.NET Lecture 5
State management
Aspnet auth advanced_cs
Forms authentication
Authorization in asp
Introduction to PicketLink
Sécurisation de vos applications web à l’aide du composant Security de Symfony
Nj 09 T2 David Frischknecht
Java Web Programming [9/9] : Web Application Security
08 asp.net session11
JavaEE Security
State management in ASP.NET
Java Cert Pki
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
Integrating Security Roles into Microsoft Silverlight Applications
Security: Odoo Code Hardening
2310 b 16
2310 b 16
Ad

Recently uploaded (20)

PPTX
Virtual and Augmented Reality in Current Scenario
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Virtual and Augmented Reality in Current Scenario
Chinmaya Tiranga quiz Grand Finale.pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Computer Architecture Input Output Memory.pptx
Environmental Education MCQ BD2EE - Share Source.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
What if we spent less time fighting change, and more time building what’s rig...
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Paper A Mock Exam 9_ Attempt review.pdf.
Unit 4 Computer Architecture Multicore Processor.pptx
Weekly quiz Compilation Jan -July 25.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
Share_Module_2_Power_conflict_and_negotiation.pptx
A powerpoint presentation on the Revised K-10 Science Shaping Paper
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
History, Philosophy and sociology of education (1).pptx
Practical Manual AGRO-233 Principles and Practices of Natural Farming

Rolebased security

  • 1. Role based Security in .NET By Sudhanshu kumar
  • 2. Role based Security in .NET Use Forms authentication to obtain and validate user credentials. Create Forms Authentication Ticket objects based on name and roles retrieved from the data store. Use Generic Principle class that provides the Rolebased authorization checking functionality. ASP.NET requires it to be stored in the HttpContext.User to relate it current application Http request. Use these objects to make authorization decisions.
  • 3. Role based Security in .NET .NET Framework provides support for the implementation of role based security which consists of Authentication (Identity) and Authorization(Rights). The .NET provides access to the user through an identity and authorization access by principal object. Identities corresponds to users and their properties.Identity classes belong to System.Security.Principal Namespace. Roles are String of role names added to a Principal to associate the current user with his assigned roles. Principal object is a collection of information about identity and roles that the current user is associated with. The System.Security.Principal Namespace contains two classes GenericPrincipal and WindowsPrincipal that are used to determine the properties of a principal object. .NET uses the Principal object to gain information about the identity and roles of a user.
  • 4. Role base Security in .NET Create a Web Application with a Logon Page. Configure the Web Application for Forms Authentication. Generate a Authentication Ticket for Authenticated Users. Construct Generic Principal and Forms Identity Objects. Use these objects to implement Role base security.
  • 5. Creating web application with Login Page Create a new ASP.NET Web Application called RoleBasedSecurity. Rename WebForm1.aspx to Logon.aspx. Add controls to Logon.aspx to create a logon form. Set the “Text Mode” property of the password Text Box control to Password. In Solution Explorer, right-click “RoleBasedSecurity” and click Add a Web Form. Enter Default.aspx as the new form's name. Set it as a start up page.
  • 6. Creating a web application with Login Page
  • 7. Application’s Web.Config file <authentication mode="Forms"> <forms loginUrl="logon.aspx" name="authCookie" timeout="60" path="/"> </forms> </authentication> -----------------------------------------------<authorization> <deny users="?" /> <allow users="*" /> </authorization>
  • 8. Generate Authentication Ticket for Authenticated Users The authentication ticket is a type of cookie used by the ASP.NET “Forms Authentication Module” (System.Web.Security) namespace. Add “using System.Web.Security” namespace to the login.aspx webform1 class. Add the following private method to the login.aspx’s WebForm1 class called IsAuthenticated and GetRoles. These methods will be used in authenticating the user and getting his identity and roles.
  • 9. Generate Authentication Ticket for Authenticated Users private bool IsAuthenticated( string username, string password ) { // This code would typically validate the user name and password // combination against SQL or some other database and return true // or false based on the credentials found in the database. return true; } private string GetRoles( string username, string password ) { // GetRoles method get the role list from database, and returns //A pipe delimited string containing roles. This format is //Convenient for storing roles in authentication ticket return "Senior Manager|Manager|Employee"; }
  • 10. Generating Authentication Ticket for Users private 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) } }
  • 11. Creating GenericPrincipal & FormsIdentity objects Implement Application AuthenticateRequest event handler in Global.asax file. Add the following using statements to the top of the Global.asax file: using System.Web.Security; using System.Security.Principal; Create GenericPrincipal and FormsIdentity objects based on information contained within the authentication ticket.
  • 12. GenericPrincipal & FormsIdentity objects protected void Application_AuthenticateRequest(Object sender,EventArgs e) { // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if(null == authCookie) { return; // There is no authentication cookie. } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch(Exception ex) { return; // Log exception details (omitted for simplicity) } if(authTicket == null) { return;// Cookie failed to decrypt. } // Ticket contains pipe delimited string of role names. string[] roles = authTicket.UserData.Split(new char[]{'|'}); FormsIdentity id = new FormsIdentity( authTicket ); // Create an Identity object // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles); Context.User = principal; // Attach the principal object to the current HttpContext object }
  • 13. Testing 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;
  • 14. Testing the application (Coding Default.aspx) private void Page_Load(object sender, System.EventArgs e) { IPrincipal p = HttpContext.Current.User; Response.Write( "Authenticated Identity is: " + p.Identity.Name ); Response.Write( "<p>" ); if ( p.IsInRole("Senior Manager") ) Response.Write( "User is in Senior Manager role<p>" ); else Response.Write( "User is not in Senior Manager role<p>" ); if ( p.IsInRole("Manager") ) Response.Write( "User is in Manager role<p>" ); else Response.Write( "User is not in Manager role<p>" ); if ( p.IsInRole("Employee") ) Response.Write( "User is in Employee role<p>" ); else Response.Write( "User is not in Employee role<p>" ); if ( p.IsInRole("Sales") ) Response.Write( "User is in Sales role<p>" ); else Response.Write( "User is not in Sales role<p>" ); }