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

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


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>


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


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.