![](/img/trans.png)
[英]How to get admin roles that I am a member of, from Microsoft Graph using .Net Client SDK?
[英]Get all users and their roles(including name and value) from Azure application using Microsoft Graph SDK
我需要在 Azure 应用程序中获取所有用户及其角色(包括角色名称和角色值)。
我所做的是检索所有用户并包含appRoleAssignments
。 问题是在appRoleAssignment
对象数组中,每个角色只有appRoleId
。
由于首先要获取所有用户,然后为每个用户中的每个appRoleAssignment
以通过appRoleAssignment
Id 检索角色所需的数据,需要进行大量 http 调用。
如何优化从 Azure 检索所有用户及其角色?
我认为可以使用batching
并将所有用户及其角色(包括角色名称和角色值)的逻辑组合到单个 API 调用中,但不知道该怎么做。
这就是我现在所拥有的:
var users = await graphClient.Users
.Request()
.Expand("appRoleAssignments")
.GetAsync();
据我所知,没有办法通过一次 API 调用将用户角色分配记录与应用角色名称一起获取。
我可以理解,如果您想为所有用户获取上述信息,那将是很多请求并导致性能不佳。 我想你可以在你的目录中获取所有应用角色信息,并获取所有角色分配记录,通过使用AppRoleId
将它们一一匹配。我为你编写了一个简单的控制台应用程序,只需尝试以下代码:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
namespace graphsdktest
{
class Program
{
static void Main(string[] args)
{
var clientId = "";
var clientSecret = "";
var tenantID = "";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authenticationProvider);
var roleResult = graphClient.ServicePrincipals.Request().Select(app => new { app.AppRoles }).Top(999).GetAsync().GetAwaiter().GetResult();
var appRoleList = new List<AppRole>();
var userRoleAssigments = new List<User>();
var RolePageIterator = PageIterator<ServicePrincipal>
.CreatePageIterator(graphClient, roleResult, (app) =>
{
if (app.AppRoles.GetEnumerator().MoveNext())
{
foreach (var appRole in app.AppRoles)
{
appRoleList.Add(appRole);
}
}
return true;
});
//get all app role information
RolePageIterator.IterateAsync().GetAwaiter().GetResult();
var roleAssigmentResult = graphClient.Users.Request().Expand("appRoleAssignments").GetAsync().GetAwaiter().GetResult();
var RoleAssigmentPageIterator = PageIterator<User>
.CreatePageIterator(graphClient, roleAssigmentResult, (user) =>
{
userRoleAssigments.Add(user);
return true;
});
//get all role assigment records
RoleAssigmentPageIterator.IterateAsync().GetAwaiter().GetResult();
foreach (var user in userRoleAssigments)
{
if (user.AppRoleAssignments.Count > 0)
{
Console.WriteLine("app role assigment of user :" + user.DisplayName);
foreach (var ras in user.AppRoleAssignments)
{
var roleName = (ras.AppRoleId.ToString().Equals("00000000-0000-0000-0000-000000000000") ? "Default Access" : appRoleList.Find(item => item.Id == ras.AppRoleId).DisplayName);
Console.WriteLine("roleID:" + ras.AppRoleId + " appName:" + ras.ResourceDisplayName + " roleName:" + roleName);
}
}
}
}
}
}
根据我的测试,整个请求大约需要 9 秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.