仅当主体可以访问导航树的各个组件(无论是基于角色还是基于策略)时,我才希望显示它们.
I would like to display components of a navigation tree only if a principal has access to those components (whether roles or policy based).
在上一个问题中,我将获得属于控制器和动作的自动过滤器列表.一旦有了IHttpContextAccessor的实例,并因此有了ClaimsPrincipal,我将如何测试该主体是否可以通过上述所有授权过滤器列表?
In the previous question I will have a List of the autorization filters which belong to a controller and action. Once I have an instance of the IHttpContextAccessor and therefore the ClaimsPrincipal, how might I test if the principal would pass all the above mentioned list of authorization filters?
也就是说,如果我模拟了以下内容:
That is, if I mocked up something like:
var mockAuthFilter = new AuthorizationFilterContext(...);
foreach (IAsyncAuthorizationFilter filter in filterListForGivenAction)
{
await filter.OnAuthorizationAsync(mockAuthFilter);
问题是-我该如何测试对OnAuthorizationAsync的任何调用是否失败?
The question is - how might I test if any calls to OnAuthorizationAsync have failed?
或者,是否有一种更好的方法可以完全确保导航树仅显示基于AuthorizeAttribute(策略和/或角色)被授权查看其主体的节点/叶子.
Alternatively, would there be a better approach altogether to ensure the navigation tree only displays nodes/leaves for which the principal is authorized to view based on the AuthorizeAttribute (policy and/or roles).
推荐答案
如果我仔细阅读了AuthorizationFilterContext属性的注释-
It was written there if I had looked closely enough at the annotations on the properties of AuthorizationFilterContext -
[结果]-将Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result设置为授权过滤器中的非null值将使过滤器管道的其余部分短路.
[Result] - Setting Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result to a non-null value inside an authorization filter will short-circuit the remainder of the filter pipeline.
因此该方法最终是:
private async Task<bool> IsValid(IEnumerable<IAsyncAuthorizationFilter> filters, ActionContext actionContext)
{
var context = new AuthorizationFilterContext(actionContext, filters.Cast<IFilterMetadata>().ToList());
foreach (var f in filters)
{
await f.OnAuthorizationAsync(context);
if (context.Result != null)
{
return false;
}
}
return true;
}
这篇关于测试对IAsyncAuthorizationFilter.OnAuthorizationAsync的调用是否失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!