在.NET Core 1.0 MVC中的视图中使用授权策略的任何方法?

Daa*_*ath 17 asp.net asp.net-mvc authorization asp.net-core-mvc asp.net-core

我知道在控制器中,您可以[Authorize("policyName")]毫无问题地编写,但有没有办法在视图中使用策略?我不想User.IsInRole(...)每次都想要授权一些HTML.

编辑:

这是一些代码

Startup.cs - 政策声明

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

管理控制器

[Authorize("testPolicy")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

导航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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 19

我发现此链接可能会有所帮助: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>
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,资源将是您的视图模型,您可以使用与在基于资源的授权期间检查的方式完全相同的方式调用AuthorizeAsync;

@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>
}
Run Code Online (Sandbox Code Playgroud)

  • 不确定在 1.0 或 2.0 中,但在核心 3.0 中,身份验证检查应该是 `@if ((await AuthorizationService.AuthorizeAsync(User, "PolicyName")).Succeeded)` - 请注意 `Succeeded` 的最终属性检查。 (2认同)

Chr*_*ris 17

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

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

<li policy="testPolicy"><a asp-controller="Admin" asp-action="Index">Admin</a></li>
Run Code Online (Sandbox Code Playgroud)

  • 迄今为止最干净的方法 - 这应该更新为随着技术的进步成为真正的答案。 (2认同)
  • +1 很棒的解决方案!对于新接触 TagHelpers 的开发人员,您需要在视图或 _ViewImports 文件中注册标记帮助程序,如下所示:`@addTagHelper *, YourAssemblyName` 阅读更多信息:https://learn.microsoft.com/en-us/aspnet/core/ mvc/views/tag-helpers/intro?view=aspnetcore-5.0#managing-tag-helper-scope (2认同)