简体   繁体   English

如何根据Azure AD组进行授权?

[英]How to do Authorization based on Azure AD groups?

Hi I am trying to implement Azure Groups based authorization in my .net core app.您好,我正在尝试在我的 .net 核心应用程序中实施基于 Azure 组的授权。 I have more groups like 100 to 200. I have added policies to add authorization.我有更多的组,比如 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
                });
            });

Then然后

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

This will return more than 100 groups.这将返回 100 多个组。 Now in policy I want to include all these groups.现在在政策中我想包括所有这些群体。 Is hard coding in config file all the groups will better way?在配置文件中对所有组进行硬编码会更好吗? Also my JWT token has only hasgroups:true rather than group ids.此外,我的 JWT 令牌只有 hasgroups:true 而不是组 ID。 So how can I authorize based on groups?那么如何基于组进行授权呢? can someone help me to find good way?有人可以帮我找到好方法吗? thanks谢谢

According to my test, if you just want to use groups based authorization, please refer to the following code:根据我的测试,如果你只想使用groups based authorization,请参考下面的代码:

  1. change Startup.cs更改 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. Add the following code in the controller or method在controller或方法中添加如下代码
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
            }

}

For more details, please refer to the sample更多详情,请参考样本

I'm working on a blazor server application and have been struggling with exactly this issue so I thought I'd post my solution here:) In the AuthorizationPolicyBuilder , call the .RequireClaim() method and specify the string "groups" and the ObjectId of your security group.我正在处理blazor服务器应用程序并且一直在努力解决这个问题所以我想我会在这里发布我的解决方案:)在AuthorizationPolicyBuilder中,调用.RequireClaim()方法并指定字符串"groups"ObjectId您的安全组。

Before this works though, you have to go into your不过,在此之前,您必须先将 go 输入您的

Azure portal -> Azure Ad -> app registrations -> token configurations -> add groups claim. Azure 门户 -> Azure 广告 -> 应用注册 -> 令牌配置 -> 添加组声明。

Make sure you check off the checkbox in Security Groups and the Group ID checkbox in { ID, Access, SAML }确保选中安全组中的复选框和{ ID, Access, SAML }中的组 ID 复选框

I don't know if this is best practice, but it worked for me:)我不知道这是否是最佳做法,但它对我有用:)

Here's the code from Startup.cs这是 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));
        });

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 .Net 核心 Web API 中进行 Azure AD 组授权? - How to do Azure AD groups authorization in .Net core web API? 如何使用 C# WEBAPI(基于令牌).netcore 进行身份验证和授权 Azure AD 应用程序 - How to do Authentication & Authorization Azure AD App, using C# WEBAPI (token based) .netcore 如何在 .net 核心应用程序中进行基于组的授权? - How to do authorization based on groups in .net core app? Web API中具有令牌的Azure AD和基于组的授权 - Azure AD and Group-based authorization with token in Web API 如何将Asp.Net身份与Azure AD授权结合在一起 - How to combine Asp.Net Identity with Azure AD Authorization 用户的Azure AD安全组 - azure AD Security groups of a User .Net Core Azure AD Cloud 如何登录用户并访问他们的 Azure AD 安全组以确定他们是否在一个组中 - .Net Core Azure AD Cloud how to get logged in user and access their Azure AD Security Groups to determine if they are in a group 如何在 AspNet Core 3 中将 Azure AD 身份验证与基于 SQL 的角色管理结合使用? - How do I use Azure AD authentication with SQL based role management in AspNet Core 3? 如何在 AWS Lambda 中进行 Azure 广告身份验证? - How to do Azure Ad authentication in AWS Lambda? Azure AD多租户WebApi承载授权配置 - Azure AD Multitenant WebApi Bearer Authorization Configuration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM