MVC Dynamic Page Permissions Using Authorize Attri

2020-05-18 01:59发布

问题:

I'm working on setting up my user permissions for my company's site, and we have several different roles and permissions that will have to be created. I have found some awesome information on creating the actual roles and groups, as well as how to implement them from here. However, this still requires the roles to be hard-coded into the authorize tag, is there a way to dynamically populate the authorize tag, so that I can have a page on the site that I can quickly assign different permissions to different pages, without having to just back into the code and modify the permission set for every single page I create?

回答1:

Implement the following custom authorise attribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public CustomAuthorizeAttribute (params string[] roleKeys) 
        {
            var roles = new List<string>();
            var allRoles = (NameValueCollection)ConfigurationManager.GetSection("CustomRoles");
            foreach(var roleKey in roleKeys) {
                roles.AddRange(allRoles[roleKey].Split(new []{','}));
            }

            Roles = string.Join(",", roles);
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectResult("~/Error/AcessDenied");
            }
        }
    }

Then add the following to the web.config

<section name="CustomRoles" type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

and then, as an example

 <CustomRoles>
    <add key="UsersPagePermission" value="HR,Accounts,Developers" /> 
  </CustomRoles>

The on your controller or action or in the global filters (whichever you prefer :)) add the attribute

e.g.

[CustomAuthorize("UsersPagePermission")]
public class UserController : Controller

This will allow you to modify the web.config rather than code to change permissions.