在 Asp.Net Core 上的 Razor 页面中检查登录用户 AuthorizePolicy

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

我正在寻找这个

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

但我不是在检查角色之后检查策略,就像您在控制器中这样做一样。

[Authorize(Policy = Policies.RequireAdmin)]

这似乎与提出的问题相似

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

该页面的示例:

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

因此完整视图包含:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

// Your HTML elements and i.e.:
@if (await AuthorizationService.AuthorizeAsync(User, "RequireAuthenticatedUser"))
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

更简洁地说:

@inject Microsoft.AspNetCore.Authorization.IAuthorizationService authorizationService

@if (await authorizationService.AuthorizeAsync(User, null, "RequireAuthenticatedUser"))
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

看来AuthorizeAsync()需要资源参数,但在我的例子中可以传递null。

使用 Dot net core 2.0 AuthorizationService.AuthorizeAsync 不再是 returns 布尔值,它 returns 是 AuthorizationResult。 dot net core 2.0 的工作版本将是这样的:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@if ((await AuthorizationService.AuthorizeAsync(User, "RequireAuthenticatedUser")).Succeeded)
{
     <li><a asp-area="" asp-controller="Roles" asp-action="Index">Roles</a></li>
}

如果你打算在多个视图中使用它,那么你最好实现自定义 RazorPage:

public abstract class MyRazorPage<T> : RazorPage<T>
{
    public async Task<bool> HasPolicyAsync(string policyName)
    {
        var authorizationService = Context.RequestServices.GetService(typeof(IAuthorizationService)) as IAuthorizationService;
        bool isAdmin = (await authorizationService.AuthorizeAsync(User, policyName)).Succeeded;
        return isAdmin;
    }
}

然后打开_ViewImports.cshtml并添加下一条指令:

@inherits MyRazorPage<TModel>

现在您可以从任何视图调用 HasPolicyAsync() 方法:

    if (await HasPolicyAsync(Policies.RequireAdmin))
    {
        <h2>Admin is authorized</h2>
    }

这样看起来会简洁很多

现在在大多数情况下最好使用 Tag Helpers 处理。 您可以像这样使用它:

<li policy="@MyGroups.Administrators">
....

所以不再是 Magic Strings :-)

参见:https://www.davepaquette.com/archive/2017/11/05/authorize-tag-helper.aspx