任何人都可以告诉我如何在mvc3中为所有操作方法实现基于角色的授权。现在在我的应用程序中,我还没有编写任何代码来跟踪用户角色。
仅在应用程序的主菜单中检查角色以构建菜单,但是当他键入url时我想拒绝用户访问。我正在考虑实现属性。任何人都可以给我建议。
提前致谢
答案 0 :(得分: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
}