我知道在控制器中,你可以写[Authorize(“policyName”)]没有问题,但有什么办法在视图中使用策略?我宁愿不要每次使用User.IsInRole(…)来授权一些
HTML.
编辑:
这是一些代码
Startup.cs – 政策声明
services.AddAuthorization(options => { options.AddPolicy("testPolicy",policy => { policy.RequireAuthenticatedUser() .RequireRole("RoleOne","RoleTwo","RoleThree") .RequireClaim(ClaimTypes.Email); }); });
管理控制器
[Authorize("testPolicy")] public class AdminController : Controller { public IActionResult Index() { return View(); } }
导航栏HTML
<div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a asp-controller="Home" asp-action="Index">Home</a></li> <!-- I want to implement my policy here. --> @if (User.IsInRole("...")) { <li><a asp-controller="Admin" asp-action="Index">Admin</a></li> } </ul> @await Html.PartialAsync("_LoginPartial") </div> </div>
解决方法
我发现这个可能有帮助的链接:
https://docs.asp.net/en/latest/security/authorization/views.html
该页面的示例:
@if (await AuthorizationService.AuthorizeAsync(User,"PolicyName")) { <p>This paragraph is displayed because you fulfilled PolicyName.</p> }
In some cases the resource will be your view model,and you can call AuthorizeAsync in exactly the same way as you would check during resource based authorization;
@if (await AuthorizationService.AuthorizeAsync(User,Model,Operations.Edit)) { <p><a class="btn btn-default" role="button" href="@Url.Action("Edit","Document",new {id= Model.Id})">Edit</a></p> }