MVC动态页面权限使用授权属性?

我正在为我公司的网站设置我的用户权限,并且我们有几个不同的角色和权限必须创建。 我发现了一些关于创建实际角色和组的真棒信息,以及如何从这里实现它们。 然而,这仍然需要将角色硬编码到授权标签中,是否有动态填充授权标签的方法,以便我可以在网站上拥有一个页面,以便我可以快速为不同的页面分配不同的权限,而无需不得不回到代码中并修改我创建的每个页面的权限集?


实现以下自定义授权属性。

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");
            }
        }
    }

然后将以下内容添加到web.config

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

然后,作为一个例子

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

在你的控制器或动作或全局过滤器(无论你喜欢:))添加属性

例如

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

这将允许您修改web.config而不是更改权限的代码。

链接地址: http://www.djcxy.com/p/90163.html

上一篇: MVC Dynamic Page Permissions Using Authorize Attribute?

下一篇: ASP.NET MVC Forms Authentication + Authorize Attribute + Simple Roles