Reputation: 5594
I am writing a bespoke web system in MVC4, part of this system requires an Admin user to manage roles and users in the company to provide access and permissions to certain areas of the system. The system has modules in the system:
Sales Production
The admin team would like the ability to create roles in the system and apply permissions to those roles. E.g. Sales role would be denied access to production but the Sales Manager can have read only access to Production.
I am looking for an example of the best approach to managing this for a single admin screen. Admin needs to
Also how would I implement it at a Controller level as the roles need to be dynamically assigned?
[Authorize(Roles="Sales")] // needs to be dynamic
public ActionResult SalesIndex(){
return View();
}
Any ideas would be appreciated
Thanks
Upvotes: 2
Views: 4603
Reputation: 124696
One way to do this is to have a data model with two levels of roles:
GroupRoles (e.g. Sales). Users are members of group roles, i.e. there is an M-N relationship Users - GroupRoles.
PermissionRoles. Represent fine-grained permissions for resources or actions or resources controlled by the application. There is an M-N relationship between GroupRoles and PermissionRoles.
You would then have a custom admin UI to assign Users to GroupRoles and GroupRoles to PermissionRoles.
You would also have a custom RoleProvider that "flattens" this model, i.e. the GetRolesForUser
method returns all PermissionRoles for a user (via his GroupRole membership).
You can then use the standard .NET APIs for authorization, and don't need custom Authorize attributes:
[Authorize(Roles="SomeAction")] // for an MVC Controller
[PrincipalPermission(SecurityAction.Demand, Role = "SomeAction")] // For a method in the BLL
Thread.CurrentPrincipal.IsInRole("SomeAction") // in code
Upvotes: 0
Reputation: 6050
You need to create custom AuthorizeAttribute
like this
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var userIdentity = httpContext.User.Identity;
if (!userIdentity.IsAuthenticated)
return false;
var rd = httpContext.Request.RequestContext.RouteData;
string currentAction = rd.GetRequiredString("action");
if(currentAction == "SalesIndex")
{
return IsUserIsInRoleForTheView(userIdentity.Name);
}
return true;
}
}
[CustomAuthorize]
public ActionResult SalesIndex()
{
return View();
}
Upvotes: 3