Search code examples
azureazure-active-directorymicrosoft-identity-platformmicrosoft-identity-web

How use AddMicrosoftIdentityWebApiAuthentication without appsettings section?


I am implementing an Azure Active Directory in a .NET 5 API. I currently have this API perfectly running on .NET Core 2.2.

This is the old working code:

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
    .AddAzureADBearer(options =>
    {
         options.Instance = "https://login.microsoftonline.com/";
         options.Domain = backOfficeADDomain;
         options.TenantId = backOfficeADTenantId;
         options.ClientId = $"api://{backOfficeADAPIClientId}";
         options.ClientSecret = backOfficeADAPISecret;
    });

But since the update to .NET 5 I get this warning:

'AzureADAuthenticationBuilderExtensions.AddAzureADBearer(AuthenticationBuilder, Action)' is obsolete: 'This is obsolete and will be removed in a future version. Use AddMicrosoftWebApiAuthentication from Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.'

So I tried updating it to this:

services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");

It seems that an "AzureAd" section in the appsettings.json is the only way to pass the credentials. How can I manually enter the Instance, domain, ClientId, etc..? I don't use the appsettings.json, all the data is manually retrieved from AzureKeyVault.

Thank you!


Solution

  • Ok, I found it!

    It's actually really easy:

    IConfigurationSection azureAdSection = _configuration.GetSection("AzureAd");
    
    azureAdSection.GetSection("Instance").Value = "https://login.microsoftonline.com/";
    azureAdSection.GetSection("Domain").Value = backOfficeADDomain;
    azureAdSection.GetSection("TenantId").Value = backOfficeADTenantId;
    azureAdSection.GetSection("ClientId").Value = backOfficeADAPIClientId;
    azureAdSection.GetSection("ClientSecret").Value = backOfficeADAPISecret;
    
    services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");
    

    It seems that after a whole day of complex code refactoring my brain couldn't comprehend such an easy solution.

    Note that I also had to remove the "api://" from the clientId. It looks like the new version adds it automatically. It tried to validate "api://api://".