【问题标题】:How to display parts of Razor Page depending on the Active Directory Security Group如何根据 Active Directory 安全组显示 Razor 页面的部分内容
【发布时间】:2021-10-20 20:00:10
【问题描述】:

我有一个 Razor 页面项目,其中 Index 页面有一个指向 Settings 页面的链接。我想只允许属于 Azure Active Directory 中 APP-Administrator 安全组的用户访问 Settings 页面。访问 Index 页面的所有用户都已在 Azure Active Directory 上经过身份验证

  1. 如何使指向Settings 页面的链接仅对APP-Administrator 组中的用户可见。
  2. 如何阻止非管理员用户直接使用 URL(例如 https://myapp.myorg.com/settings)访问 Settings 页面。

注意:本题与How to add Azure Active Directory authentication only to some Razor Pages in a web app?无关

【问题讨论】:

标签: c# azure asp.net-core azure-active-directory razor-pages


【解决方案1】:

为了解决这个问题,我写了一个标签助手;

[HtmlTargetElement(Attributes = "policy")]
public class PolicyTagHelper : TagHelper
{
    private readonly IAuthorizationService authService;
    private readonly IHttpContextAccessor httpContextAccessor;

    public PolicyTagHelper(IAuthorizationService authService, IHttpContextAccessor httpContextAccessor)
    {
        this.authService = authService;
        this.httpContextAccessor = httpContextAccessor;
    }

    public string Policy { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        if (!(await authService.AuthorizeAsync(httpContextAccessor.HttpContext.User, Policy)).Succeeded)
            output.SuppressOutput();
    }
}

这样,您可以简单地添加一个策略属性,使该 html 在用户无权访问时消失。

<a asp-page="/Settings" policy="administrators" ... >Settings</a>

// Startup;

services.AddRazorPages(options => {
    options.Conventions
        .AuthorizePage("/Settings", "administrators");
});

剩下的唯一问题是如何识别管理员用户,这可能看起来像;

// Startup
services.AddAuthorization(options => {
    options.AddPolicy("administrators", policy => policy.RequireRole("[domain]\[group]"));
});

【讨论】:

    【解决方案2】:

    场景:使用托管在 Azure 中的混合 Razor Page Web 应用程序和 React 前端。一些页面将在服务器上处理,而其他页面将仅通过 APIM 中托管的 API 在客户端上处理。我们已经使用内置的服务器端代码来登录/注销

    @if (User.Identity.IsAuthenticated) a class='@navItemCss' asp-area='MicrosoftIdentity' asp-controller='Account' asp-action='SignOut'

    a class='flex' asp-area='MicrosoftIdentity' asp-controller='Account' asp-action='SignIn'

    我们可以利用页面上的授权属性和方法,以及围绕 Azure Ad 中的组的自定义策略。 [授权(Policy = 'Partner-Portal-Admins')]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 2018-09-04
      相关资源
      最近更新 更多