Any way to use Authorization Policies in a view in .NET Core 1.0 MVC?

瘦欲@ 提交于 2019-12-03 10:10:05

I found this link which may be helpful: https://docs.asp.net/en/latest/security/authorization/views.html

Examples from that page:

@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>
}

I ended up creating a tag helper to conditionally hide the element it's associated with.

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

Usage

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

This is one of the big improvements in ASP Core when you can inject the identity to all pages in the startup file:

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

In Startup.cs:

 services.AddIdentity<ApplicationUser, IdentityRole>()

EDIT: Ok I misread the post, you already knew this :) - ill leave it anyway if someone can use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!