How to work with Roles (asp.net) without hard coding them?

When roles / roles are created, I do not want to change the code.

if (HttpContext.Current.User.IsInRole("Super Admin") ||
    HttpContext.Current.User.IsInRole("Admin") ||
    HttpContext.Current.User.IsInRole("Support"))
{
    if (HttpContext.Current.User.IsInRole("Admin"))
    {
        ListBox1.DataSource = Roles.GetAllRoles().Except(
            new[] { "Super Admin" });

    }
    if (HttpContext.Current.User.IsInRole("Support"))
    {
        ListBox1.DataSource = Roles.GetAllRoles().Except(
            new[] { "Super Admin", "Admin" });
    }
    fillDropDownCustomers();
}
+5
source share
4 answers

Roles work by assigning meaning to what the user can do. Roles do not change, but the behavior for these roles. Ultra dynamic solutions are usually redundant.

So maybe you have the following roles

  • Super admin
  • Support
  • Administrator

You may have different actions (this will depend on your system)

  • View
  • Edit
  • Confirm

Etc

  • Super Admin [View, Modify, Approve]
  • Support [View]
  • Admin [View, Edit]

Actions. , , -, . - . , (Database Driven to make modifiable)

, " ", , , , .

, .

  • UserRole [ID, UserName, RoleID] ( , , DISTINCT , , : UserRole , .)
  • [ID, ]
  • [ID, ]
  • RoleAction [ID, RoleID, ActionID] ( RoleID ActionID)

, .. _. , () , RoleAction < >

Action Role. . , , , Unit Test, .

+2

:

public static class MyRoles
{
    public const string Admin = "Admin";
    public const string SuperAdmin = "Super Admin";
    public const string Support = "Support";
}

:

if (HttpContext.Current.User.IsInRole(MyRoles.SuperAdmin) ||
    HttpContext.Current.User.IsInRole(MyRoles.Admin) ||
    HttpContext.Current.User.IsInRole(MyRoles.Support))
{
+4

- . - IoC , .

0

, . , .

Another option is to add role names to the configuration file. You must use application settings or a custom configuration class that inherits from ConfigurationSection. See here how http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

This way you can change the role names in the web.config file and you will not need to update any code or republish the project.

0
source

All Articles