asp.net - 如何在asp.net mvc5中创建动态角色

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

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

最佳答案

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

为了做到这一点。

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 分配给 Controller 操作

    [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 表中设置所有应用程序内容,如源( Controller )和函数(操作)。

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

6.将用户分配给角色。

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

关于asp.net - 如何在asp.net mvc5中创建动态角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53912692/

相关文章:

c# - 控件。添加评论?

c# - 如何将 google oauth 2.0 限制为仅在 ASP.NET Core Web 应用程序中的特定域?

c# - 在创建 View 中从数据库中填充下拉列表

asp.net mvc - 如何更新tinyMCE中的下拉列表

c# - LINQ to Entities 无法识别方法 'Int16 Parse(System.String)'

c# - Routes.AppendTrailingSlash 排除部分路线

javascript - Uncaught ReferenceError : show value is not defined(Only for mobile device)

ajax - ASP.Net MVC : Can you use Data Annotations/Validation with an AJAX/jQuery call?

javascript - 在 IE11 中出现 Javascript 严重错误

文件夹 App_Code 中的 C# 访问类