为嵌套在组中的用户角色设置授权
本文关键字:用户 角色 设置 授权 嵌套 | 更新日期: 2023-09-27 18:11:36
我正在做一个项目,我第一次使用角色授权,我不能让它工作。
问题是,当一个新用户被创建时,项目以一种方式被设置,他们被添加到一个组。这些组包含一个或多个角色。例如,组"ReadOnly"包含角色"userReadOnly"answers"groupsReadOnly"(此用户可以进入页面用户和组,查看数据,但不能编辑数据)
我得到的部分是控制器中的[Authorize(Roles = "..., ...")]
和视图中的@if(user.IsInRole("...")
,但是当我将其添加到项目中时,事情停止工作。我知道我需要创建一个自定义的AccountRoleProvider
,但在这里我卡住了。我不明白如何做到这一点,我不明白如何适应(标准)供应商在网上找到适合我的项目。如果能向正确的方向提示一下,或者解释一下提供商的实际工作,我将不胜感激。
要创建自定义授权过滤器,您需要在解决方案中创建一个文件夹,并在其中添加一个名为AuthorizedRoles.cs的文件。
AuthorizedRoles.cs文件如下:
sealed class AuthorizedRoles : ActionFilterAttribute
{
public string Roles { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var status = false;
string[] roles = Roles.Split(',');
var currentUserRole = Session.UserRole; // Get here the role of the user
var Role = "";
switch (currentUserRole)
{
case 1:
Role = "Role1";
break;
case 2:
Role = "Role2";
break;
case 3:
Role = "Role3";
break; // Check here for more role
default:
break;
}
if (Role != ""){
foreach (var role in roles)
{
if (role.Contains(currentRoleName))
{
status = true;
}
}
}
if (status == false)//That means user is not in the role, so redirect it to the new controller returning a view showing information that you are not autorized
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
//The request can be ajax callso it will redirect to another ajax method
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "ControllerName",
action = "AjaxActionName",
area = ""
}));
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "ControllerName",
action = "ActionName",
area = ""
}));
}
}
base.OnActionExecuting(filterContext);
}
}
重定向方法将像;
public ActionResult ActionName()
{
return View(); //Create view for this action
}
public JsonResult AjaxActionName()
{
return Json(new { status = false, message = "Unauthorized access." }, JsonRequestBehavior.AllowGet);
}
在任何需要检查的方法上面都可以调用自定义授权过滤器:
//This method will execute only if the user have Role1 and Role2 other wise redirected to other no permission methods before the action executes.
[AuthorizedRoles(Roles = "Role1,Role2")]
public ActionResult NeedPermissionAction(int id)
{
}