Trent Stewart
Trent Stewart

Reputation: 881

How to handle role authorization for users having multiple roles in ASP.NET MVC?

I am trying to find the best way to structure my security roles in ASP.NET MVC.

Basically the Roles are static (Administrator, Client, Technician) but what they can do in each section is configurable, Add/Edit/Delete/View.

For example you are able to configure a Client's security to specific areas like User Accounts.

A user can be a combination of any roles, so it is possible to be a Client and a Technician and have the combined privlages of both users.

What would be a suitable way to go about doing this in ASP.NET MVC?

Upvotes: 0

Views: 2871

Answers (3)

Pradeep Kumar Das
Pradeep Kumar Das

Reputation: 891

  1. Initially you can check the user exist in how many roles?
  2. Create a view to show the Roles and write the message "please select a role to proceed "
  3. After choose the user type proceed the user as the selection.

Upvotes: 0

Val
Val

Reputation: 539

I would provide you this resolution:

  • Data Base

    1. Users ([PK]Id, Name, etc.)
    2. Roles ([PK]Id, Name, Description, etc.)
    3. UserRoles ([PK]UserId, [PK] RoleId)

Users table stores information about users, like their names, emails, etc. Roles stores information about rolesm like its name, description, etc. UserRoles is just look-up table which you can use to tie specific user to specific role.

  • Code

In order to let your code to work with these tables, you can add your custom role provider where you will have enough facility with 2 methods that will be: public override string[] GetRolesForUser(string username) and public override bool IsUserInRole(string username, string roleName).

  • Usage

When you'll complete, you simply can use Authorize attributes [Authorize(Roles = "Administrators")] to check if user has access to specific action or controller or you can use Razor verification in order to show/hide some html based on users role @User.IsInRole("Administrator")


Please check following links for more info

Upvotes: 1

Satpal
Satpal

Reputation: 133403

This is how we did it

public enum YourUserRoles
{
    None = 0,
    Admin = 1,
    Consumer = 2
}

public class YourAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
    private readonly YourUserRoles[] _acceptedRoles;

    public YourAuthorizeAttribute(params VoicelrUserRoles[] acceptedroles)
    {
        _acceptedRoles = acceptedroles;
    }

    public YourAuthorizeAttribute(params bool[] allowAll)
    {
        if (allowAll[0])
            _acceptedRoles = new[] { VoicelrUserRoles.Admin, VoicelrUserRoles.Consumer };
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (SessionHelper.UserInSession == null)//user not logged in
        {
            string retUrl = filterContext.HttpContext.Request.RawUrl;
            FormsAuthentication.SignOut();
            filterContext.Result =
                 new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary {{ "controller", "home" },
                                             { "action", "index" },
                                             { "returnUrl",    retUrl } });//send the user to login page with return url
            return;
        }
        if (!_acceptedRoles.Any(acceptedRole => SessionHelper.UserInSession.Roles.Any(currentRole => acceptedRole == currentRole)))
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Error.cshtml"
            };
        }
    }
}

[YourAuthorize(YourUserRoles.Client )]
public ActionResult Whatever()
{
  ....
}

Upvotes: 1

Related Questions