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

问题描述 投票:0回答:1

[嗨,我正在尝试在.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();

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

c# asp.net-core azure-active-directory authorization
1个回答
0
投票

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

  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

© www.soinside.com 2019 - 2024. All rights reserved.