0

我正在使用azure广告图api从活动目录中提取用户配置文件数据。我所有的输入参数都是正确的,令牌也是用下面的代码生成的。但它不会将用户配置文件对象作为response.response.IsSuccessStatusCode始终为false。这可能是我的错误?azure广告图api不拉用户信息

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); 
       } 
+0

你有解决这个问题?如果你仍然有问题,请随时告诉我。 –

回答

3

您正在使用应用程序令牌检索用户信息。由于令牌中没有这种类型的登录用户信息,因此预计会出现此错误。要使用该应用程序令牌读取用户信息,我们需要使用users\{id | userPrincipalName}如下面的reuqest更换me

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

应用令牌通常在使用客户端凭证流动,这获得一个后台程序服务中使用。 关于此流程的更多细节,可以参考here

如果您想使用keyworld,我们需要使用我们可以使用的代表令牌,如the OAuth 2 code grant flow。并根据previews thread,似乎你正在开发一个Web应用程序。请查看代码示例here关于使用Azure AD Graph进行开发以显示配置文件。这里是相对码获取令牌:

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)); 

,这里是约authencation secnario一个有用的文档Azure的AD:

Authentication Scenarios for Azure AD

+0

好吧,稍微更一般一点,当你想为* app *获取一个令牌时,使用客户端凭证,并且登录用户无关紧要。当您的应用的用户在Azure AD中没有足够的权限时,也可以使用它,但您希望通过您的应用授予他们部分访问权限。 – juunas

相关问题