如何基于 Azure AD 组进行授权?

How to do Authorization based on Azure AD groups?

您好,我正在尝试在我的 .net 核心应用程序中实施基于 Azure 组的授权。我有更多的组,如 100 到 200。我已添加策略以添加授权。

services.AddAuthorization(options =>
            {   
                options.AddPolicy("GroupsCheck", policy =>
                {
                    policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                    policy.Requirements.Add(new GroupsCheckRequirement("11b250bf-76c0-4efe-99f2-2d781bae43bb")); //currently hard coded but want to include all the groups returned from MS graph
                });
            });

然后

 GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
 var groupList = await client.Users[userId].TransitiveMemberOf.Request().GetAsync();

这将 return 超过 100 个组。现在在政策中我想包括所有这些群体。在配置文件中对所有组进行硬编码会更好吗?此外,我的 JWT 令牌只有 hasgroups:true 而不是组 ID。那么如何基于组进行授权呢?有人可以帮我找到好方法吗?谢谢

根据我的测试,如果你只想使用基于组的授权,请参考以下代码:

  1. 改变Startup.cs
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
      .AddAzureAD(options => configuration.Bind(configSectionName, options));
  services.Configure<AzureADOptions>(options => configuration.Bind(configSectionName, options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.NameClaimType = "preferred_username";
 // Use the groups claim for populating roles
              options.TokenValidationParameters.RoleClaimType = "groups";
});
 services.AddMvc(options =>
      {
          var policy = new AuthorizationPolicyBuilder()
              .RequireAuthenticatedUser()
              .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
            })
        .SetCompatibilityVersion(CompatibilityVersion.Latest);

  1. 在控制器或方法中添加如下代码
if(User.Identity.IsAuthenticated){
   if (User.IsInRole("<group id>"))
            {
                 // do other action

            }
            else if (User?.FindFirst("_claim_names")?.Value != null)
            {

                /* call Graph API to check if the user is in the group

                     for example
                     GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();
var memberOfGroups= await client.Me.TransitiveMemberOf.Request().GetAsync();


                    do
                    {
                        bool breakLoops = false;

                        foreach (var directoryObject in memberOfGroups.CurrentPage)
                        {
                            if (directoryObject is Group)
                            {
                                Group group = directoryObject as Group;
                                if (group.Id == "<group id>") {

                                    breakLoops = true;
                                    break;

                                }

                            }
                        }
                        if (breakLoops)
                        {
                            break;
                        }
                        if (memberOfGroups.NextPageRequest != null)
                        {
                            memberOfGroups = await memberOfGroups.NextPageRequest.GetAsync();
                        }
                        else
                        {
                            memberOfGroups = null;
                        }
                    } while (memberOfGroups != null);

               */


            }
            else {

                // do not have enough permissions
            }

}

详情请参考sample

我正在开发一个 blazor 服务器应用程序并且一直在努力解决这个问题所以我想我会 post 我的解决方案在这里 :) 在 AuthorizationPolicyBuilder,调用 .RequireClaim() 方法并指定字符串 "groups" 和安全组的 ObjectId

不过,在此之前,您必须进入

Azure portal -> Azure Ad -> app registrations -> token configurations -> add groups claim.

确保选中安全组中的复选框和 { ID, Access, SAML }

中的组 ID 复选框

我不知道这是否是最佳做法,但它对我有用:)

这是来自 Startup.cs

的代码
public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

        services.AddControllersWithViews(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("groups", "<insert object id for group>")
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        });

    }