.netazuremicrosoft-graph-apiihostedservicemicrosoft.identity.web

Prgrammatically set Azure AD client secret in Dotnet Worker service calling Microsoft Graph


I have a dotnet (v8) worker service that calls Microsoft Graph to list users and groups. I am using Microsoft.Identity.Web. All the Azure AD (Microsoft Entra) app registrations and permissions are configured correctly as I am able to make the calls successfully with client id and client secret in the appsettings.json. However I want to load the client secret from Key Vault at runtime. How do I do this?

This is the code to add graph.

        services
        .AddTokenAcquisition(isTokenAcquisitionSingleton: true)
        .Configure<MicrosoftIdentityApplicationOptions>(configuration.GetSection("AzureAd"))
        .AddInMemoryTokenCaches()
        .AddHttpClient();

    services.AddMicrosoftGraph(configuration.GetSection("MicrosoftGraph"));

The appsettings.json is as below.

  "AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "TenantId": "xxx",
      "ClientId": "xxx",
      "ClientCredentials": [
      {
        "SourceType": "ClientSecret",
        "ClientSecret": "secretvalue"
      }
    ],
    "Domain": "xxx.onmicrosoft.com"
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0"
  },

Solution

  • I got it working. Posting here in case someone else has the same problem

    services
    .Configure<MicrosoftIdentityApplicationOptions>(o =>
    {
        azureSection.Bind(o);
        o.ClientCredentials.First().ClientSecret = "secret";
    });