[英]Exception in Query Azure Active AD users using C# code
我已在 Azure Active Diretcory 中注冊了一個應用程序並使用以下代碼:
<appSettings>
<add key="TenantId" value="b1f9cb25-7c7a-4ecd-96c1-513c2b42c350"/>
<add key="TenantName" value="myTentantName.onmicrosoft.com"/>
<add key="ClientId" value="d82c0c6a-8c14-4c42-8aca-60c79fcfc9b4"/>
<add key="ClientSecret" value="27?_MOh_qM633Hcccct;cw:@*$9ojcsNxve)rYI"/>
</appSettings>
internal class Settings
{
public const string ResourceUrl = "https://graph.microsoft.com";
public static string TenantId => ConfigurationManager.AppSettings["TenantId"];
public static string TenantName => ConfigurationManager.AppSettings["TenantName"];
public static string ClientId => ConfigurationManager.AppSettings["ClientId"];
public static string ClientSecret => ConfigurationManager.AppSettings["ClientSecret"];
public static string AuthString => "https://login.microsoftonline.com/" + TenantName;
}
類 AuthenticationHelper
public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication()
{
Uri servicePointUri = new Uri(Settings.ResourceUrl);
Uri serviceRoot = new Uri(servicePointUri, Settings.TenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(
serviceRoot,
async () => await AcquireTokenAsyncForApplication());
return activeDirectoryClient;
}
private static async Task<string> AcquireTokenAsyncForApplication()
{
AuthenticationContext authenticationContext = new AuthenticationContext(Settings.AuthString, false);
ClientCredential clientCred = new ClientCredential(Settings.ClientId, Settings.ClientSecret);
AuthenticationResult authenticationResult =
await authenticationContext.AcquireTokenAsync(
Settings.ResourceUrl,
clientCred);
string token = authenticationResult.AccessToken;
return token;
}
主類
var client = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
try
{
var users = await client.Users.OrderBy(user => user.DisplayName).ExecuteAsync();
var foundUser = await client.Users.Where(user => user.ObjectId == "d62d8c6a-dc69-46c1-99c4-36cd672f0c12").ExecuteAsync();
foreach (var user in users.CurrentPage)
{
Console.WriteLine(user.DisplayName + " " + user.ObjectId);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
我在主類中遇到錯誤:
var users = await client.Users.OrderBy(user => user.DisplayName).ExecuteAsync();
System.InvalidOperationException: 處理此請求時出錯。 ---> System.PlatformNotSupportedException:此平台不支持安全二進制序列化。
我參考官方示例獲得成功: Azure-Samples / active-directory-dotnet-graphapi-console
唯一的區別是ResourceUrl
不是https://graph.microsoft.com
。 正確的值為https://graph.windows.net
。
那講得通。 因為您正在嘗試使用AD Graph而不是Microsoft Graph
更新
與代碼一樣,您正在獲取帶有客戶端憑據的令牌。 因此,您獲得的令牌只有應用程序權限。 因此,您需要在 Azure 門戶中添加和授予應用程序權限:
現在發現了錯誤的資源問題,代碼運行良好(我自己測試過)。 剩下的問題是什么?
https://graph.windows.net/Directory.Read.All
。 最后,您可以獲得同時使用 AAD Graph API 和 MS Graph API 的用戶。 建議移至后者,因為前者將被棄用。 查看將 Azure AD Graph 應用程序遷移到 Microsoft Graph 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.