【问题标题】:How to do Authorization based on Azure AD groups?如何基于 Azure AD 组进行授权?
【发布时间】:2020-03-27 23:49:29
【问题描述】:

您好,我正在尝试在我的 .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。那么如何根据组进行授权呢?有人可以帮我找到好方法吗?谢谢

【问题讨论】:

  • 根据情况,我建议您将项目更改为使用Azure AD应用程序基于角色的身份验证。我们可以为 AD 组创建自定义应用程序角色。但请注意,如果要为组分配应用角色,则需要拥有 Azure AD 高级计划。更多详情请参考docs.microsoft.com/en-us/azure/architecture/…和stackoverflow.com/questions/58515744/…
  • 谢谢。我们计划使用基于组的授权而不是角色。
  • 您还有其他顾虑吗?如果您没有其他顾虑,您能接受答案吗?它可能会帮助更多有类似问题的人

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


【解决方案1】:

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

  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

【讨论】:

    【解决方案2】:

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

    在此之前,你必须进入你的

    Azure 门户 -> Azure 广告 -> 应用注册 -> 令牌配置 -> 添加组声明。

    确保选中安全组中的复选框和{ 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));
            });
    
        }
    

    【讨论】:

    • 当您的 sn-p 说 &lt;insert object id for group&gt; 时,您的意思是来自 AAD 的 GUID,对吗?每次我尝试访问该站点时,我仍然会收到Access Denied。有什么建议吗?
    • 另一个快速问题@kevinruder,您的应用注册/api 权限是否添加了GroupMember.Read.All?一些文档暗示这是必需的。
    • 最后一个问题,很抱歉问了这么多,但您是否必须获得管理员同意才能在您的应用注册中访问GroupMember.Read.All?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多