I'm developing an ASP.NET webforms application with pages which displays information based on the authorization level of the authenticated user (very typical). I will write a simple example of the issue I'm facing:

Let's pose I want to have a page with 4 buttons:

1- "OnlyForAdmins" button. 2- "OnlyForManagersAndAdmins" button 3- "Guest" button 4- "Authenticated" button

Depending on the permission level of the visitor, one or several buttons must be displayed. Right now in code behind buttons are handled in the following way:

public void Page_Load(object sender, EventArgs e)
    if (HttpContext.Current.User.Identity.IsAuthenticated)
        Athenticated.Visible = true;
    if (HttpContext.Current.User.IsInRole("Admins"))
        OnlyForAdmins.Visible = true;
    if (HttpContext.Current.User.IsInRole("Manager") || HttpContext.Current.User.IsInRole("Admins"))
        OnlyForManagersAndAdmin.Visible = true;

While this works, honestly I think that this approach is rather inflexible, having to add more "ifs" for every new role I introduce.

I wonder if there exist approaches to handle this kind of problems. I'd be grateful if someone can enlighten me.

Thank you.


I'd do it this way:

A user can hold a number of Roles within your application (including none). These will be retrieved from an external data store.

Any control within your application is available to any number of Roles. These might be statically defined or loaded from an external data store.

A Control becomes "available" when the current User's Role set intersects with the Roles required to access that Control.

For example:

Button1 might be "tagged" with the "Admin" and "Manager" roles.
Button2 might be tagged with just the "Admin" role.

Manager3 might have the "Authenticated" and "Manager" roles. They can access Button1.

Admin4 will have the "Authenticated" and "Admin" roles. They can access both buttons.

Guest5 has no Roles at all (being unauthenticated) and can use neither button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.