Checking login user AuthorizePolicy in Razor page on Asp.Net Core

Thomas Andreè Wang picture Thomas Andreè Wang · May 29, 2016 · Viewed 10.7k times · Source

I'm looking for a variant of this

@if (SignInManager.IsSignedIn(User) && User.IsInRole(Roles.Administrator))
{
    <div id="editArticle">

but instead of checking after the role I'm after a check into the policy much like you would in a controller by doing this.

[Authorize(Policy = Policies.RequireAdmin)]

Answer

James P picture James P · May 29, 2016

This seems similar to question asked here

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