I want to use Microsoft Graph API in ASP.NET Core MVC app to get information about current user. However, when the Graph Service Client attempts to fetch the user data in the controller (trying to populate entraIDUser
variable), the request seems to hang indefinitely and never completes.
How can I resolve this issue and ensure the Graph API request completes successfully?
Here is what I have:
-
my app is registered with Microsoft Identity platform, and
User.Read
Delegated API permission is granted -
controller function:
[HttpGet]
public async Task<IActionResult> Index()
{
try
{
var graphServiceClient = GetGraphServiceClient();
var entraIDUser = await graphServiceClient.Me.GetAsync();
return View();
}
catch (Exception ex)
{
_logger.LogError("An error occured when trying to return Index page: " + ex.Message);
return StatusCode(500, "An error occured when trying to return Index page");
}
}
GetGraphServiceClient
function that creates an instance of GraphServiceClient:
private GraphServiceClient GetGraphServiceClient()
{
var scopes = new[] { "User.Read" };
var tenantId = _configuration.GetValue<string>("AzureAd:TenantId");
var clientId = _configuration.GetValue<string>("AzureAd:ClientId");
var options = new DeviceCodeCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
ClientId = clientId,
TenantId = tenantId,
DeviceCodeCallback = (code, cancellation) =>
{
Console.WriteLine(code.Message);
return Task.FromResult(0);
},
};
var deviceCodeCredential = new DeviceCodeCredential(options);
var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);
return graphClient;
}
Recognized by Microsoft Azure Collective