I am using azure ad graph api to pull user profile data from active directory. All my input parameters are correct and token is also generated with the below code. But it is not giving user profile object as response.response.IsSuccessStatusCode is always false. What may be my mistake here?
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);
}
You were using the the application-token to retrieve the user info. The error is expected since there is no such kind of sign-in user info in the token. To read user info using the application-token, we need to replace
me
usingusers\{id | userPrincipalName}
like the reuqest below:The application-token is usually used in a daemon service which acquire using by Client Credentials flow. More detail about this flow, you can refer here.
If you want to use the
me
keyworld, we need to use the delegate-token which we can acquire using like the OAuth 2 code grant flow. And based on the previews thread, it seems that you were developing with an web app. Please check the code sample here about developing with Azure AD Graph to show the profile. Here is the relative code to acquire the token:And here is an helpful document about authencation secnario for Azure AD:
Authentication Scenarios for Azure AD