我按照https://docs.asp.net/en/latest/security/authorization/policies.html实施了基于自定义政策的授权。
当通过控制器中的[Authorize]访问它时,最终成功。但是,当我尝试在我的视图中使用它时,如下所示。我遇到了context.Resource为null的问题。
我是mvc的新手,所以感谢任何帮助。
查看
@if (await AuthorizationService.AuthorizeAsync(User, "IsRegisteredUser"))
{
<li><a asp-area="" asp-controller="Solution" asp-action="Index">Solutions</a></li>
}
授权处理程序
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsRegisteredUserRequirement requirement)
{
if(context.User.Identity.IsAuthenticated)
{
var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
}
return Task.CompletedTask;
}
答案 0 :(得分:1)
在视图中,您可以使用AuthorizeAsync的重载方法和使用ViewContext设置的资源参数:
<div class="row mainFeatures" id="AboutUs">
<div class="col-sm-4 col-md-4 col-sm-4 col-xs-12">
<div class="img-thumbnail">
<img src="~/images/experience-icon.png" width="85" height="88" alt="secure">
<div class="caption">
<h4>Experience</h4>
<p>Our experience in various industries benefits our clients when it comes to understanding their problem or requirements.</p>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4 col-sm-4 col-xs-12">
<div class="img-thumbnail">
<img src="~/images/quality-icon.png" width="85" height="88" alt="secure">
<div class="caption">
<h4>Quality</h4>
<p>We believe in quality not quantity. We take the time to ensure our products and services are as reliable as possible.</p>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4 col-sm-4 col-xs-12">
<div class="img-thumbnail">
<img src="~/images/user-friendly-icon.png" width="85" height="88" alt="secure">
<div class="caption">
<h4>User-Friendly</h4>
<p>Most importantly, our products are easy to use and functional.<br /></p>
</div>
</div>
</div>
</div>
然后在处理程序中,您可以将资源转换为ActionContext基类,ViewContext和AuthorizationFilterContext将从该基类继承:
await AuthorizationService.AuthorizeAsync(User, ViewContext, "YourPolicyName");
然后您可以访问HttpContext,ModelState和RouteData。