Search code examples
c#azure-active-directorymicrosoft-graph-apiopenid-connectmicrosoft-graph-teams

How to get Microsoft Graph client in a ASP.NET Core Web App?


Context

I have a working ASP.NET Core Web App, which uses Entra ID authentication:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddInMemoryTokenCaches();

For this authentication to work I've created an Azure App registration and the configuration of the authentication contains the respective Client ID, Client secret and Tenant Id. I've added the necessary graph permissions for the Azure App registration.

I would like to call the Graph API in this web applicationfor example:

var meeting = new OnlineMeeting() { Subject = "demo meeting" };
var result = await graphClient.Me.OnlineMeetings.PostAsync(meeting);

All sample code I found is either uses device flow to get the graphClient, or uses depreciated or breaking changed authentication to create the graphClient

Question

How can I create a graphClient?


Solution

  • Your appsettings.json should contain something like this:

    {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "ClientId": "<client_app_id>",
        "TenantId": "common",
    
       // To call an API
       "ClientCredentials": [
        {
          "SourceType": "ClientSecret",
          "ClientSecret":"<client_secret>"
        }
      ]
     },
     "GraphV1": {
        "BaseUrl": "https://graph.microsoft.com/v1.0",
        "Scopes": ["<scope>"]
        }
    }
    

    Add NuGet packages Microsoft.Identity.Web and Microsoft.Identity.Web.GraphServiceClient.

    To initialize Graph service client:

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services
      .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
      .AddMicrosoftIdentityWebApp(builder.Configuration, "AzureAd")
          .EnableTokenAcquisitionToCallDownstreamApi()
              .AddMicrosoftGraph(builder.Configuration.GetSection("GraphV1"))
          .AddInMemoryTokenCaches();
    

    Now in your controller, add GraphServiceClient into the constructor, it should be automatically resolved.

    public HomeController(ILogger<HomeController> logger, GraphServiceClient graphClient)
    {
        _logger = logger;
        _client = graphClient;
    }
    

    Be aware that with client secret, you can't call me endpoint, you need to call users/{user_id}.

    var meeting = new OnlineMeeting() { Subject = "demo meeting" };
    var result = await graphClient.Users["{user_id}"].OnlineMeetings.PostAsync(meeting);