【问题标题】:How to create dynamic role in asp.net mvc5如何在asp.net mvc5中创建动态角色
【发布时间】:2019-05-23 13:45:37
【问题描述】:

我想在 ASP.NET MVC 5 中创建一个动态角色。我不想在授权属性中创建硬编码角色。我想稍后创建角色。这是我招聘的测试。你有示例代码或视频 在这种情况下? 就在 ASP.NET MVC 5 中。 提前感谢您的帮助

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity identity


    【解决方案1】:

    你的意思是你需要动态授权。

    为了做到这一点。

    1.您需要再添加两个表(身份表除外)。

    1. AppContent(列:{Id、Resource、Function、Description})
    2. RoleRights(列:{Id、RoleName、AppContentId)。

    2.创建CustomAuthorizeAttribute

    [AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class CustomAuthorize : AuthorizeAttribute
    {
        //Custom named parameters for annotation
        public string Source { get; set; }//Controller Name
        public string Function { get; set; }//Action Name
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        { 
            //Is user logged in?
            if (httpContext.User.Identity.IsAuthenticated)
            {
    
                 if ((!string.IsNullOrEmpty(ResourceKey)) && (!string.IsNullOrEmpty(OperationKey)))
                {
                    //There are many ways to store and validate RoleRights 
                    //1.You can store in Database and validate from Database.
                    //2.You can store in user claim at the time of login and validate from UserClaims.
                    //3.You can store in session validate from session
    
                    //Below I am using database approach.
                    var loggedInUserRoles = ((ClaimsIdentity) httpContext.User.Identity).Claims
                                            .Where(c => c.Type == ClaimTypes.Role)
                                            .Select(c => c.Value);
    
                    //logic to check loggedInUserRoles has rights or not from RoleRights table
                    return db.RoleRights.Any( x=> x.AppContent.Source == Source && x.AppContent.Function == Function && loggedInUserRoles.Contains( x.AppContent.RoleName));
    
                }
    
            }
            //Returns true or false, meaning allow or deny. False will call HandleUnauthorizedRequest above
    
            return base.AuthorizeCore(httpContext);
        }
    
        //Called when access is denied
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //User isn't logged in
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(filterContext);
                return;
    
            }
            //User is logged in but has no access
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(new { controller = "Account", action = "NotAuthorized" })
                );
            }
    
        }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // Check for authorization
    
            if (string.IsNullOrEmpty(this.Source) && string.IsNullOrEmpty(this.Function))
            {
                this.Source = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                this.Function = filterContext.ActionDescriptor.ActionName;
            }
    
            base.OnAuthorization(filterContext);
        }
    }
    

    3.将 CustomAuthorizeAttribute 分配给控制器操作

        [CustomAuthorize(Source= "Branch", Function = "Index")]
        public ActionResult Index()
        {
            return View(model);
        }
    
        [CustomAuthorize(Source = "Branch", Function = "Details")]
        public ActionResult Details(long? id)
        {
            return View(branch);
        }
    
        [CustomAuthorize(Source = "Branch", Function = "Create")]
        public ActionResult Create()
        { 
            return View();
        }
    

    4.在 AppContent 表中设置所有应用程序内容,例如 Source(Controller) 和 Function(Action)。

    5.将 AppContents 分配给一个角色以允许该角色访问此内容。

    6.将用户分配给角色。

    7.运行应用程序并进行测试。

    【讨论】:

    • 不错的答案!你能告诉我 Resource 和 OperationKey 是从哪里来的吗?
    • 另外,您知道如何将这个属性分成两部分吗?一个适用于类的,为所有动作指定“区域”和“控制器”?还有一个适用于方法的第二个,它将通过 relfection 或其他方式获得 ActionName ? (我猜这也可以为类属性完成)我可以自己做,但我对如何链接方法属性以获取类属性并结合存储在两个属性中的信息来应用授权有点迷茫,比如您在 CustomAttribute 中所做的事情。我正在努力避免重复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 2017-04-24
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多