Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)]
like image 408
Thomas Andreè Wang Avatar asked May 29 '16 11:05

Thomas Andreè Wang


People also ask

How do I Authorize my razor page?

One way to control access in your Razor Pages app is to use authorization conventions at startup. These conventions allow you to authorize users and allow anonymous users to access individual pages or folders of pages. The conventions described in this topic automatically apply authorization filters to control access.

How would you apply an authorization policy to a controller in an ASP.NET Core application?

Role-Based Authorization in ASP.NET Core You can specify what roles are authorized to access a specific resource by using the [Authorize] attribute. You can even declare them in such a way that the authorization evaluates at the controller level, action level, or even at a global level. Let's take Slack as an example.

How does Authorize attribute work in ASP.NET Core?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.


1 Answers

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>
}
like image 100
James P Avatar answered Oct 01 '22 18:10

James P