Aug 25 2023 01:24 AM
I have a .NET MVC core V6 app which I am trying to use Azure AD authentication and Graph API with.
Initially I ran the following code without explicitly adding Microsoft.Graph from Nuget
using MyApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.AspNetCore.Http;
using Azure.Identity;
using Microsoft.Extensions.Azure;
namespace MyApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[Authorize]
public async Task<IActionResult> Index()
{
var userID = User.Identity.Name;
}
There is no objection to the Using Microsoft.Graph; statement at the top & authentication happens, with userID getting set correctly. The problems happen when I try to add graph syntax from https://developer.microsoft.com/en-us/graph/graph-explorer to get the groups I belong to
The command https://graph.microsoft.com/v1.0/me/transitiveMemberOf/microsoft.graph.group?$count=true suggests the following code
var graphClient = new GraphServiceClient(requestAdapter);
var result = await graphClient.Me.TransitiveMemberOf.GraphGroup.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
This causes 2 errors which stop compilation:
requestAdapter is not defined and
TransitiveMemberOf does not contain a definition for GraphGroup.
So far I have tried a number of fixes.
var options = new DeviceCodeCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
ClientId = clientId,
TenantId = tenantId,
DeviceCodeCallback = (code, cancellation) =>
{
return Task.FromResult(0);
},
};
var deviceCodeCredential = new DeviceCodeCredential(options);
var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);
fixes the graphClient error;
2.Adding Graph.Client explicitly via Nuget gets rid of the error , but causes Program.cs to crash at the following command
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
with the error 'Unable to load one or more of the requested types.
Could not load type 'Microsoft.Graph.IBaseRequest' from assembly 'Microsoft.Graph.Core, Version=3.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
3 Removing the graph API via nuget and setting the query syntax to
var result = await graphClient.Me.TransitiveMemberOf.Request().GetAsync();
lets the app build, but it seems to run into a loop , or just really slowly
Any advice on getting this working will be gratefully received.
Thanks in advance
Best Regards Richard