1

すべてのアクション メソッドに対して mvc3 でロール ベースの承認を実装する方法を教えてください。今まで、アプリケーションでユーザー ロールを追跡するコードを書いていません。

アプリケーションのメイン メニューでのみロールをチェックしてメニューを構築していますが、ユーザーが URL を入力したときにアクセスを拒否したくありません。属性を実装することを考えていました。

前もって感謝します

4

1 に答える 1

0

以下のことを試してみてください。

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-10-14T11:16:08.807 に答える