如何使用 Microsoft Graph API 获取 .net 核心应用程序中的所有授权组? [英] How to use Microsoft Graph API to get all the groups for Authorization in .net core application?

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

问题描述

我正在从事 .net 核心项目.我正在尝试使用 AD 组实现授权.我的要求是,我在azure 广告中有很多组.如果当前用户属于 azure ad 中的任何可用组,那么我想授权这些用户访问以 .net core 应用程序编写的 api.我试过如下.我在下面添加了两个类

 公共类 IsMemberOfGroupHandler : AuthorizationHandler{受保护的覆盖任务 HandleRequirementAsync(AuthorizationHandlerContext 上下文,IsMemberOfGroupRequirement 要求){var groupClaim = context.User.Claims.FirstOrDefault(claim => claim.Type == "groups" &&claim.Value.Equals(requirement.GroupId, StringComparison.InvariantCultureIgnoreCase));if (groupClaim != null)上下文.成功(要求);返回 Task.CompletedTask;}}公共类 IsMemberOfGroupRequirement : IAuthorizationRequirement{公共只读字符串 GroupId;公共只读字符串 GroupName;公共 IsMemberOfGroupRequirement(string groupName, string groupId){组名 = 组名;GroupId = groupId;}}

下面是我的创业班.

 services.AddAuthorization(options =>{var adGroupConfig = new List();_configuration.Bind("AdGroups", adGroupConfig);foreach(adGroupConfig 中的 var adGroup)options.AddPolicy(adGroup.GroupName,政策 =>policy.AddRequirements(new IsMemberOfGroupRequirement(adGroup.GroupName, adGroup.GroupId)));});

以上代码检查配置文件中可用的组.现在我的要求是使用 microsoft graph api 来获取所有可用的组.我找不到任何方法来处理这个要求.有人可以帮我弄这个吗?任何帮助,将不胜感激.谢谢

解决方案

请先查看 此代码示例 ,它使用 OpenID Connect 登录用户并使用 MSAL 获取 Microsoft Graph API 令牌以退休组.

如果通过编辑清单将您的应用程序配置为接收组声明:

<代码>{...errorUrl":空,groupMembershipClaims":SecurityGroup",...}

登录用户所属的安全组的对象 ID 在令牌的组声明中返回.

<块引用>

如果用户所属的组数超过了超限限制(SAML 令牌为 150,JWT 令牌为 200),则 Microsoft Identity Platform 不会发出令牌中的组声明.相反,它在令牌中包含一个超额声明,指示应用程序查询图形 API 以检索用户的组成员身份.

<代码>{..._claim_names":{组":src1"},{_claim_sources":{src1":{端点":[从中获取该用户的组成员资格的图形 URL]"}}...}

所以你可以遵循这个过程:

<块引用>

  1. 检查声明 _claim_names,其中一个值为组.这表示超额.

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

  3. 如果没有找到,请查看用户组的组声明.

当然,您可以直接调用 Microsoft Graph API 来退出当前用户的组而无需使用 group claim :

https://docs.microsoft.com/en-us/graph/api/user-list-memberof?view=graph-rest-1.0&tabs=http

然后您可以根据该组进行授权.例如,如果使用策略:

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

GroupsCheckRequirement.cs:

公共类 GroupsCheckRequirement : IAuthorizationRequirement{公共字符串组;公共组检查要求(字符串组){this.groups = 组;}}

GroupsCheckHandler.cs:

公共类 GroupsCheckHandler : AuthorizationHandler{私有只读 ITokenAcquisition tokenAcquisition;私有只读 IMSGraphService graphService;公共 GroupsCheckHandler(ITokenAcquisition tokenAcquisition, IMSGraphService MSGraphService){this.tokenAcquisition = tokenAcquisition;this.graphService = MSGraphService;}受保护的覆盖异步任务 HandleRequirementAsync(AuthorizationHandlerContext 上下文,GroupsCheckRequirement 要求){string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });User me = await graphService.GetMeAsync(accessToken);IList<组>组 = 等待 graphService.GetMyMemberOfGroupsAsync(accessToken);变量结果 = 假;foreach (var group in groups){if (requirement.groups.Equals(group.Id)){结果=真;}}如果(结果){上下文.成功(要求);}}}

然后使用策略:

[Authorize(Policy = "GroupsCheck")]

I am working on .net core project. I am trying to implement authorize using AD groups. My requirement is, I have many groups in the azure ad. If the current user belongs to any of the available groups in azure ad then I want to authorize those users to access apis written in .net core application. I tried as below. I have added below two classes

 public class IsMemberOfGroupHandler : AuthorizationHandler<IsMemberOfGroupRequirement>
    {
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context, IsMemberOfGroupRequirement requirement)
        {
            var groupClaim = context.User.Claims
                 .FirstOrDefault(claim => claim.Type == "groups" &&
                     claim.Value.Equals(requirement.GroupId, StringComparison.InvariantCultureIgnoreCase));

            if (groupClaim != null)
                context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

 public class IsMemberOfGroupRequirement : IAuthorizationRequirement
    {
        public readonly string GroupId;
        public readonly string GroupName;

        public IsMemberOfGroupRequirement(string groupName, string groupId)
        {
            GroupName = groupName;
            GroupId = groupId;
        }
    }

Below is my startup class.

 services.AddAuthorization(options =>
            {
                var adGroupConfig = new List<AdGroupConfig>();
                _configuration.Bind("AdGroups", adGroupConfig);

                foreach (var adGroup in adGroupConfig)
                    options.AddPolicy(
                        adGroup.GroupName,
                        policy =>
                            policy.AddRequirements(new IsMemberOfGroupRequirement(adGroup.GroupName, adGroup.GroupId)));
            });

Above code checks groups available in configuration file. Now my requirement is use microsoft graph api to get all the available groups. I could not find any way to handle this requirement. Can someone help me with this? Any help would be appreciated. Thanks

解决方案

Please firstly check this code sample , which use OpenID Connect to sign in users and use MSAL to get the Microsoft Graph API token to retire groups .

If config the your application to receive group claims by editing the manifest :

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

The object id of the security groups the signed in user is member of is returned in the groups claim of the token.

If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens), then the Microsoft Identity Platform 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.

{
  ...
  "_claim_names": {
    "groups": "src1"
    },
    {
   "_claim_sources": {
    "src1": {
        "endpoint":"[Graph Url to get this user's group membership from]"
        }
    }
  ...
}

So you can follow the process :

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

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

  3. 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 :

https://docs.microsoft.com/en-us/graph/api/user-list-memberof?view=graph-rest-1.0&tabs=http

You can then authorize based on that groups . For example , if using policy :

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

GroupsCheckRequirement.cs:

public class GroupsCheckRequirement : IAuthorizationRequirement
{
    public string groups;

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

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);
        }
       
    }


}

And then using policy :

[Authorize(Policy = "GroupsCheck")] 

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

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