[英]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.