MVC Dynamic Page Permissions Using Authorize Attribute?

后端 未结 1 678
甜味超标
甜味超标 2021-01-31 12:12

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 awesom

相关标签:
1条回答
  • 2021-01-31 12:48

    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.

    0 讨论(0)
提交回复
热议问题