asp.net-mvcrazorasp.net-core-mvcasp.net-identity-3

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


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)]

Solution

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