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

时间:2016-03-17 18:17:42

标签: asp.net asp.net-mvc authorization asp.net-core asp.net-core-mvc

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

编辑:

这里有一些代码

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();
    }
}

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

3 个答案:

答案 0 :(得分:18)

我发现此链接可能会有所帮助: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>
}
  

在某些情况下,资源将是您的视图模型,您可以使用与在基于资源的授权期间检查的方式完全相同的方式调用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>
}

答案 1 :(得分:13)

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

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

答案 2 :(得分:0)

当您可以将身份注入启动文件中的所有页面时,这是ASP Core的一项重大改进:

@if (User.IsInRole("Admin"))
{
    <p>
    <a asp-action="Create" asp-controller="MyController">Create New</a>
</p>
}

在Startup.cs中:

 services.AddIdentity<ApplicationUser, IdentityRole>()

编辑: 好吧,我误读了帖子,你已经知道了这一点:) - 如果有人可以使用它,就不管怎么说。