![](/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.