【问题标题】:Role based authorization in mvc3mvc3中基于角色的授权
【发布时间】:2013-10-21 20:50:01
【问题描述】:

谁能告诉我如何在 mvc3 中为所有操作方法实现基于角色的授权。到目前为止,在我的应用程序中,我还没有编写任何代码来跟踪用户角色。

仅在应用程序的主菜单中检查角色以构建菜单,但我想在他键入 url 时拒绝用户访问。我正在考虑实现属性。谁能给我建议。

提前致谢

【问题讨论】:

  • 在 OnAuthorization 授权过滤器中编写您的逻辑并放入基本控制器并将该基本控制器继承给每个控制器。

标签: asp.net-mvc-3


【解决方案1】:

试试下面的东西。

protected override void OnAuthorization(AuthorizationContext filter_context)
{
    #region If auth cookie is present
    if (auth_cookie != null)
    {
        #region IF loggedin user is a member
        if (SiteUsers.LoggedInUser.UserRole == UserRole.Buyer
            && filter_context.ActionDescriptor.ControllerDescriptor.ControllerName == "Home"
            && filter_context.ActionDescriptor.ActionName == "Index")
        {
            filter_context.Result = RedirectToAction("Index", "Home");
        }
        #endregion

        #region If loggedin user is a super admin
        else if (SiteUsers.LoggedInUser.UserRole == UserRole.Administrator && !filter_context.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(Adminstrator), false).Any())
        {
            if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(AllowAdmin), false).Any())
            {
                filter_context.Result = RedirectToAction("Home", "Admin");
            }

        }
        #endregion

        ViewBag.SiteUsers = SiteUsers;
    }
    #endregion

    #region if authorization cookie is not present and the action method being called is not marked with the [SkipAuthentication] attribute
    else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(SkipAuthentication), false).Any())
    {
        if (Request.IsAjaxRequest()) filter_context.Result = Json(new ActionOutput { Results = new List<string> { Url.Action("Signin", "Home") }, Status = ActionStatus.Error }, JsonRequestBehavior.AllowGet);
        else
            filter_context.Result = RedirectToAction("Signin", "Home");
    }
    #endregion

    #region if authorization cookie is not present and the action method being called is marked with the [SkipAuthentication] attribute
    else
    {
        SiteUsers = new ReplictivityUserDetails();
        ViewBag.SiteUsers = SiteUsers;
    }
    #endregion
}

【讨论】:

    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多