MVC Dynamic Page Permissions Using Authorize Attribute?

后端 未结 1 606
甜味超标
甜味超标 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();
                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

    and then, as an example

     
         
      
    

    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)
提交回复
热议问题