如何在ASP.NET MVC5中创建动态角色

时间:2018-12-24 11:13:01

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

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

1 个答案:

答案 0 :(得分:0)

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

为此,

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

  1. AppContent(列:{Id,资源,功能,说明})
  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分配给Controller Action

    [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(控制器)和Function(Action)。

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

6。为用户分配角色。

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