.net核心应用程序中如何基于组进行授权? [英] How to do authorization based on groups in .net core app?

查看:81
本文介绍了.net核心应用程序中如何基于组进行授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

net核心应用程序.我的要求是添加基于组的授权.我是Azure AD的用户.我属于一些以BR和AR开头的组名.仅属于AR组的用户应该能够访问我的API.目前,我的客户端应用程序是Swagger,我只能通过swagger来访问APIS.

net core application. My requirement is to add group based authorization. I am user in Azure AD. I belong to the some group names starts with BR and AR. Users belong to the AR groups only should be able to access my APIs. Currently my client application is Swagger and I am hitting APIS only through swagger.

例如,在启动时,我可以输入以下代码.

For example, In startup I can have the below code.

services.AddAuthorization(options => {
                options.AddPolicy("AR-BitBucket-User",
                        policyBuilder => policyBuilder.RequireClaim("groups",
                        "6be4f534-dcf5-489e-b57d-c7bb46be8d6b"));
            });  

在控制器中,

[Authorize("AR-BitBucket-User")]

在上述方法中,我正在硬编码,但我不想硬编码.首先,我没有获得JWT令牌中的群组信息,而是得到

In the above approach, I am hard coding but I do not want to hard code. First of all I am not getting groups info in JWT token and I am getting

hasGroups:true在我的JWT令牌中.与其进行硬编码,不如从Graph API获取它.有人可以帮我怎么做吗?我无法在互联网上获得任何相关示例.有人可以帮我吗?

hasGroups:true in my JWT token. Instead of hard coding I want to get it from Graph API. Can someone help me how to do this? I am not able to get any related example in internet. So can someone help me?

推荐答案

如果要配置应用程序以接收组声明,则需要设置"

If you want to config your application to receive group claims, you need to set the "groupMembershipClaims" value as SecurityGroup in the Manifest file.

  1. 在应用程序注册"门户上的应用程序设置页面中,单击清单"以打开嵌入式清单编辑器.

  1. In your application settings page on the Application Registration Portal , click on "Manifest" to open the inline manifest editor.

通过找到"groupMembershipClaims"设置并将其值设置为"SecurityGroup"来编辑清单.

Edit the manifest by locating the "groupMembershipClaims" setting, and setting its value to "SecurityGroup".

保存清单.

    {
      ...
      "errorUrl": null,
      "groupMembershipClaims": "SecurityGroup",
      ...
    }

为应用程序启用组声明后,Azure AD在JWT和SAML令牌中包括一个声明,该声明包含用户所属的所有组的对象标识符(objectId),包括传递组成员身份.

When the groups claim is enabled for an application, Azure AD includes a claim in the JWT and SAML tokens that contains the object identifiers (objectId) of all the groups to which the user belongs, including transitive group membership.

但是请注意,要确保令牌大小不超过HTTP 标头大小限制,Azure AD限制了它的objectId数量 包括在团体索赔中.如果用户是多个组的成员,则 超额限制(SAML令牌为150,JWT令牌为200),然后 Azure AD不会发出令牌中的组声明.相反,它 在令牌中包含超额索偿要求,该索偿指示 应用程序以查询Graph API来检索用户的组 成员资格.有关更多详细信息,请参阅

But please note that to ensure that the token size doesn't exceed HTTP header size limits, Azure AD limits the number of objectIds that it includes in the groups claim. If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens), then Azure AD does not emit the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the Graph API to retrieve the user's group membership. For more details, please refer to the blog.

所以您需要执行一些步骤:

So you need to do some process :

  1. 检查其中一个值为组的索赔_claim_names.这表明超量了.

  1. Check for the claim _claim_names with one of the values being groups. This indicates overage.

如果找到,请调用_claim_sources中指定的端点以获取用户组.

If found, make a call to the endpoint specified in _claim_sources to fetch user’s groups.

如果未找到,请查看用户所属组的组声明.

If none found, look into the groups claim for user’s groups.

当然,您可以直接调用

Of course , you can directly call Microsoft Graph API to retire current user's groups without using group claims

关于如何基于该组进行授权,可以创建策略.有关更多详细信息,请参阅文档.例如

Regarding how to authorize based on that groups, you can create a policy. For more details, please refer to the document. For example

Startup.cs

Startup.cs

    services.AddAuthorization(options =>
    {
        options.AddPolicy("CheckGroups", policy =>
            policy.Requirements.Add(new GroupsCheckRequirement("YourGroupID")));
    });
    services.AddScoped<IAuthorizationHandler, GroupsCheckHandler>();

GroupsCheckRequirement.cs:

GroupsCheckRequirement.cs:

    public class GroupsCheckRequirement : IAuthorizationRequirement
    {
        public string groups;

        public GroupsCheckRequirement(string groups)
        {
            this.groups = groups;
        }
    }

GroupsCheckHandler.cs:

GroupsCheckHandler.cs :

    public class GroupsCheckHandler : AuthorizationHandler<GroupsCheckRequirement>
    {
        private readonly ITokenAcquisition tokenAcquisition;
        private readonly IMSGraphService graphService;

        public GroupsCheckHandler(ITokenAcquisition tokenAcquisition, IMSGraphService MSGraphService)
        {
            this.tokenAcquisition = tokenAcquisition;
            this.graphService = MSGraphService;
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                  GroupsCheckRequirement requirement)
        {
            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

            User me = await graphService.GetMeAsync(accessToken);

            IList<Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

            var result = false;
            foreach (var group in groups)
            {
                if (requirement.groups.Equals(group.Id))
                {
                    result = true;
                }
            }

            if (result)
            {
                context.Succeed(requirement);
            }

        }


    }

然后使用策略:

[Authorize(Policy = "CheckGroups")] 


此外,您还可以通过ASP.NET Core中间件库来实现它.通过在TokenValidationParametersRoleClaimType属性中指定声明,asp.net中间件支持从声明填充的角色.由于groups声明包含的安全组的对象ID比实际名称要多,因此您将使用组ID而不是组名.有关更多详细信息,请参阅


Besides, you also can implement it by ASP.NET Core middleware libraries. The asp.net middleware supports roles populated from claims by specifying the claim in the RoleClaimType property of TokenValidationParameters. Since the groups claim contains the object ids of the security groups than actual names, you'd use the group ids instead of group names. For more details, please refer to the sample.

Startup.cs

Startup.cs

// The following lines code instruct the asp.net core middleware to use the data in the "groups" claim in the Authorize attribute and User.IsInrole()
            // See https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                // Use the groups claim for populating roles
                options.TokenValidationParameters.RoleClaimType = "groups";
            });

然后使用它

[Authorize(Roles = "Group-object-id")] // In controllers
// or
User.IsInRole("Group-object-id"); // In methods

这篇关于.net核心应用程序中如何基于组进行授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆