gpt4 book ai didi

c# - azure ad graph api不提取用户信息

转载 作者:行者123 更新时间:2023-12-03 05:06:19 25 4
gpt4 key购买 nike

我正在使用 azure ad graph api 从 Active Directory 中提取用户个人资料数据。我的所有输入参数都是正确的,并且 token 也是使用以下代码生成的。但它没有提供用户配置文件对象,因为 response.response.IsSuccessStatusCode 始终为 false。我在这里可能犯了什么错误?

private readonly string graphUserUrl = "https://graph.windows.net/{0}/me?api-version=1.6"
string tenantName = "Microsoft.OnMicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(clientId, appKey);
string resource = "https://graph.windows.net";
string token = "";
try
{
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
token = authenticationResult.AccessToken;
}
catch (AuthenticationException ex)
{

}

UserProfile profile;
string requestUrl = String.Format(CultureInfo.InvariantCulture,graphUserUrl,HttpUtility.UrlEncode(tenantId));
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
//HttpResponseMessage response = await client.SendAsync(request);
HttpResponseMessage response = client.SendAsync(request).Result;

// Return the user's profile in the view.
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
profile = JsonConvert.DeserializeObject<UserProfile>
(responseString);
}

最佳答案

您正在使用应用程序 token 来检索用户信息。该错误是预料之中的,因为 token 中没有此类登录用户信息。要使用应用程序 token 读取用户信息,我们需要使用 users\{id | 替换 me userPrincipalName} 就像下面的请求:

https://graph.windows.net/{tenant}/users/{id|userPrincipalName}?api-version=1.6

应用程序 token 通常在守护程序服务中使用,该守护程序服务通过客户端凭据流获取使用。更详细的这个流程,可以引用here

如果你想使用 me keyworld,我们需要使用委托(delegate) token ,我们可以使用 the OAuth 2 code grant flow 来获取它。 。并基于previews thread ,看来您正在使用网络应用程序进行开发。请查看代码示例here关于使用 Azure AD Graph 进行开发以显示配置文件。获取token的相关代码如下:

string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

这里是有关 Azure AD 身份验证安全的有用文档:

Authentication Scenarios for Azure AD

关于c# - azure ad graph api不提取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com