首页 > 解决方案 > 如何在asp.net mvc5中创建动态角色

问题描述

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

标签: asp.netasp.net-mvcasp.net-mvc-5asp.net-identityidentity

解决方案


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

为此。

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.Assign AppContents 到一个角色,允许角色访问这个内容。

6.将用户分配给角色。

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


推荐阅读