Link to home
Start Free TrialLog in
Avatar of zachvaldez
zachvaldezFlag for United States of America

asked on

Role based security

How to implement role-based security? There are pages that only few people are allowed to see and edit.
Is there any C# example of this?
ASKER CERTIFIED SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zachvaldez

ASKER

I'm using web forms. All I want to implement is a simple security check based on role when clicking a button to open a secured page.
I'm looking at the link you sent me on web forms and it seems to me it should be workable but I do have questions regarding implementing it.
The sample code that caught my eye is this...
public void Application_AuthenticateRequest( Object src , EventArgs e )
{
   if (!(HttpContext.Current.User == null))
   {
      if (HttpContext.Current.User.Identity.AuthenticationType == "Forms" )
      {
      System.Web.Security.FormsIdentity id;
      id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
      String[] myRoles = new String[2];
      myRoles[0] = "Manager";
      myRoles[1] = "Admin";
      HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id,myRoles);
      }
   }
}

Open in new window

Basically here the roles are hard coded?
when I opened my Global.ASAX, I don't see this event..  Only application start
public void Application_AuthenticateRequest( Object src , EventArgs e )
You have to add it. And yes the example is very crude. Ideally roles and their definitions should come from a database and of you are implementing a really simple solution than web.config should be used to store the roles.
I use web forms as I mentioned. I would like to see how to set it up in web config and how to access it thru code and also eventually
how to use role definitions from a database.
In that case, I would recommend that you directly follow this article : https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/roles/creating-and-managing-roles-cs

It has everything you have asked for. I know that the article is way old but if you are using WebForms then I think it is more than suitable to your requirements.
Please add the following article to above - it is actually a set of articles that will complete your requirements. At minimum do also look at: https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/roles/role-based-authorization-cs

If you have a question or need detailed understanding please let me know.
PS: Do remember to read up on my original recommended reading of Security Concepts.
The answers were thorough
Thanks for your comments :)