我将 .NET Core
与 C#
应用程序结合使用,并集成了 Azure AD 身份验证。这意味着任何 Azure AD 用户都可以登录此应用程序。现在在某个地方,我想显示当前登录用户的城市、州、国家和其他一些字段值。为此,我使用了 Microsoft Graph API ,但我无法成功获取详细信息。我收到错误 Request_ResourceNotFound
。我使用下面的 C#
代码来获取当前登录用户的数据。
var clientId = "<CLIENT_ID>"; // I have used my application client id here
var secret = "<CLIENT_SECRET>"; // I have used my client secret here
var domain = "<DOMAIN>"; // I have used domain here
var credentials = new ClientCredential(clientId, secret);
var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{domain}/");
var token = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
return Task.CompletedTask;
}));
var user = await graphServiceClient
.Me
.Request()
.GetAsync(); // Error at this line
但是当我使用graphServiceClient.Me.Request().GetAsync()
Error: Code: Request_ResourceNotFound
Message: Resource 'XXXX-XXXX-XXX-XXXX' does not exist or one of its queried reference-property objects are not present.
之前有人遇到过这种错误吗?谁能建议如何在 C# 中使用 Microsoft Graph 获取当前登录用户的数据?
最佳答案
您正在使用客户端凭据,因此没有“当前登录的用户”。它实际上是客户端凭据的全部要点,无需用户即可对应用程序进行身份验证。
使用客户端凭据时,您需要显式指定用户id
或userPrincipalName
:
var user = await graphServiceClient
.Users["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7415181d150734101b19151d1a5a1b1a191d17061b071b12005a171b19" rel="noreferrer noopener nofollow">[email protected]</a>"]
.Request()
.GetAsync();
关于c# - 获取当前用户的更多信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59561412/