gpt4 book ai didi

asp.net - 有没有办法在 .NET Core 1.0 MVC 的 View 中使用授权策略?

转载 作者:行者123 更新时间:2023-12-02 01:09:08 25 4
gpt4 key购买 nike

我知道在 Controller 中,您可以毫无问题地编写 [Authorize("policyName")] ,但是有什么方法可以在 View 中使用策略吗?我不想每次想要授权某些 HTML 时都使用 User.IsInRole(...)

编辑:

这是一些代码

Startup.cs -- 政策声明

    services.AddAuthorization(options =>
{
options.AddPolicy("testPolicy", policy =>
{
policy.RequireAuthenticatedUser()
.RequireRole("RoleOne", "RoleTwo", "RoleThree")
.RequireClaim(ClaimTypes.Email);
});
});

管理 Controller

[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>

最佳答案

我最终创建了一个标签助手来有条件地隐藏与其关联的元素。

[HtmlTargetElement(Attributes = "policy")]
public class PolicyTagHelper : TagHelper
{
private readonly IAuthorizationService _authService;
private readonly ClaimsPrincipal _principal;

public PolicyTagHelper(IAuthorizationService authService, IHttpContextAccessor httpContextAccessor)
{
_authService = authService;
_principal = httpContextAccessor.HttpContext.User;
}

public string Policy { get; set; }

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
// if (!await _authService.AuthorizeAsync(_principal, Policy)) ASP.NET Core 1.x
if (!(await _authService.AuthorizeAsync(_principal, Policy)).Succeeded)
output.SuppressOutput();
}
}

使用

<li policy="testPolicy"><a asp-controller="Admin" asp-action="Index">Admin</a></li>

关于asp.net - 有没有办法在 .NET Core 1.0 MVC 的 View 中使用授权策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com