我想自定义 System.Web.Http.AuthorizeAttribute
类,如下所示:
public class MyAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public PermissionsEnum IsPermitted { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (System.Web.HttpContext.Current.Session["Role"] == null) return false;
string rol = (string)System.Web.HttpContext.Current.Session["Role"];
if (rol == "Admin" || Roles == "Super Admin") IsPermitted = PermissionsEnum.Administration;
else IsPermitted = PermissionsEnum.Collaboration;
return base.IsAuthorized(actionContext);
}
}
[Flags]
public enum PermissionsEnum
{
Administration,
Collaboration
}
我在 Controller 中使用它:
[MyAuthorizeAttribute(IsPermitted = PermissionsEnum.Administration)]
public class PointageController : Controller
{
public ActionResult GraphesEtStatistiques()
{
return View();
}
[MyAuthorizeAttribute(IsPermitted = PermissionsEnum.Administration)]
public ActionResult Pointage()
{
return View();
}
public ActionResult Parametrage()
{
return View();
}
public ActionResult GetMessages()
{
MessagesRepository _messageRepository = new MessagesRepository();
return PartialView("_MessagesList", _messageRepository.GetAllMessages());
}
}
我的问题是,我什至可以访问 Pointage
View IsPermission=PermissionsEnum.Collaboration
!!!! 。
所以:
- 这个问题的原因是什么?
- 我该如何修复它?
最佳答案
- What is the reason of this problem?
您的问题是 IsAuthorize
方法中的逻辑不正确。
- How can I fix it?
...设置断点并调试您的 IsAuthorized 方法。
从您提供的代码来看,按照当前的结构方式,IsPermission
属性是多余的。您在装饰 Controller 时将其传递到属性中,但在 IsAuthorized
方法中,您对注入(inject)的值不执行任何操作。相反,您可以独立设置它。然后,您调用基本 AuthorizeAttribute
的 IsAuthorized
方法,并且基本属性没有您的枚举的概念。
我不确定这是否能解决您的域需求,但这至少会给您一个可以构建的功能性IsAuthorized
方法:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (System.Web.HttpContext.Current.Session["Role"] == null) return false;
string role = (string)System.Web.HttpContext.Current.Session["Role"];
if ((role == "Admin" || role == "Super Admin") //recycling your condition
&& IsPermitted == PermissionsEnum.Administration) return true;
if ((role == "Collaborator"
&& IsPermitted == PermissionsEnum.Collaborator) return true;
return false;
}
关于c# - 在 asp.net Web api 应用程序中自定义 System.Web.Http.AuthorizeAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35271881/