Reputation: 881
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
Reputation: 891
Upvotes: 0
Reputation: 539
I would provide you this resolution:
Data Base
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.
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)
.
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
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