【发布时间】:2017-01-06 23:19:32
【问题描述】:
我为我的应用程序创建了一个自定义授权属性类,以测试是否允许用户访问 API 路由。我正在测试的用户拥有该类将测试删除的所有权限,但 api 仍在运行。我做错了什么?
UserActionsDictionary 具有租户 ID 作为键和用于操作的字符串列表。
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Application {
public class HasActionAttribute : AuthorizeAttribute {
public string Actions { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext) {
UserCache userCache = HELPERS.GetCurrentUserCache();
return userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect(Actions.Split(',').ToList()).Any();
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
filterContext.Result = new HttpUnauthorizedResult("Action not allowed for the current user");
}
}
}
在控制器中。我正在测试导致授权在路由中失败的原因,它甚至不应该进入,但是通过断点,我看到测试结果是错误的。
[Authorize]
public class TestController : ApiController {
[Route("api/Test/TestRoute")]
[HttpGet]
[HasAction(Actions="Test Action")]
public dynamic Test(){
UserCache userCache = HELPERS.GetCurrentUserCache();
bool test = userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect("Test Action".Split(',').ToList()).Any();
return test;
}
}
我在这里看到很多关于类似主题的问题,但似乎没有一个能解决我在这里遇到的问题。
【问题讨论】:
-
好像你继承了错误的
AuthorizeAttribute。您需要继承自System.Web.Http而不是System.Web.Mvc(因为它是 WebAPI 控制器)。 -
@haim770 System.Web.Http 似乎没有我需要覆盖的内容。如果我必须从 System.Web.Http 继承,那么问题就变成了如何实现我想要做的事情?
-
它们确实不同,但您也可以从
System.Web.Http.AuthroizeAttribute继承时获得确切的结果。见msdn.microsoft.com/en-us/library/… 和stackoverflow.com/questions/12629530/… -
@haim770 如果我理解正确我应该这样做吗?
public string Actions { get; set; }public override void OnAuthorization(HttpActionContext actionContext) {UserCache userCache = HELPERS.GetCurrentUserCache();if (!userCache.UserActionsDictionary[userCache.CurrentTenantID.ToString()].Intersect(Actions.Split(',').ToList()).Any()) {HandleUnauthorizedRequest(actionContext);}}
标签: c# asp.net-mvc-4 authorize-attribute