我想在自定义属性中进行安全验证。一个很好的例子是,如果用户发出GET请求来检索具有给定id的实体,我想拦截属性中的该请求,将其移交给动作过滤器,然后确定用户是否可以访问它。我唯一的问题是如何检索实体ID。我无法在属性声明中传递它,因为它会被初始化一次而不是每个请求。相反,我想给我的自定义属性一个url模式,就像你给HttpGet或HttpPost一样,让它解决上下文的url参数,从而得到一个实体id。
这是我的属性:
public class RequireProjectAccessAttribute : TypeFilterAttribute
{
public string UrlPattern { get; set; }
public RequireProjectAccessAttribute(string urlPattern) : base(typeof(RequireProjectAccessFilter))
{
UrlPattern = urlPattern;
Arguments = new object[] { urlPattern };
}
private class RequireProjectAccessFilter : IAsyncActionFilter
{
private readonly ICurrentSession _currentSession;
private readonly string _urlPattern;
public RequireProjectAccessFilter(ICurrentSession currentSession, string urlPattern)
{
_currentSession = currentSession;
_urlPattern = urlPattern;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var projectId = /* some magic to resolve _urlPattern against the current url parameter values */
if (/* user doesn't have access to project */)
{
context.Result = new UnauthorizedResult();
}
else
{
await next();
}
}
}
}
以下是我想用它的方法:
[Route("api/[controller]")]
public class ProjectsController : BaseController
{
public ProjectsController()
{
}
[RequireProjectAccess("{projectId}")]
[HttpGet("{projectId}")]
public JsonResult GetById(int projectId)
{
/* retrieve project */
}
}
答案 0 :(得分:1)
您只需提供应包含值的路由键,然后在HttpContext
对象上使用扩展方法GetRouteValue(string key)
。
var projectId = context.HttpContext.GetRouteValue(_routeKey)?.ToString();
这意味着您的属性将如下所示:
public class RequireProjectAccessAttribute : TypeFilterAttribute
{
public string RouteKey { get; set; }
public RequireProjectAccessAttribute(string routeKey) : base(typeof(RequireProjectAccessFilter))
{
RouteKey = routeKey;
Arguments = new object[] { routeKey };
}
private class RequireProjectAccessFilter : IAsyncActionFilter
{
private readonly ICurrentSession _currentSession;
private readonly string _routeKey;
public RequireProjectAccessFilter(ICurrentSession currentSession, string routeKey)
{
_currentSession = currentSession;
_routeKey = routeKey;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var projectId = context.HttpContext.GetRouteValue(_routeKey)?.ToString();
if (/* user doesn't have access to project */)
{
context.Result = new UnauthorizedResult();
}
else
{
await next();
}
}
}
}
并用作此(通知我只传递路由键的名称):
[RequireProjectAccess("projectId")]
[HttpGet("{projectId}")]
public JsonResult GetById(int projectId)
{
/* retrieve project */
}