Search code examples
azure-active-directoryadalazure-ad-msal

How to handle AppTokenCache of multi-tenant daemon service application using MSAL.NET


Is it possible to use the MSAL.NET authentication library to handle multiple AppTokenCaches that are generated by a multi-tenant daemon service app (i.e. the Client Credential grant)?

In this scenario, I have to build (n) number of confidential client applications based on tenant ids and I need to maintain the tokens.

var confidentialClientApplication_001 = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithTenantId("TenantId__001")
                .WithClientSecret(clientSecret)
                .Build();

var confidentialClientApplication_002 = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithTenantId("TenantId__002")
                .WithClientSecret(clientSecret)
                .Build();

...
...
...

var confidentialClientApplication_999 = ConfidentialClientApplicationBuilder
                    .Create(clientId)
                    .WithTenantId("TenantId__999")
                    .WithClientSecret(clientSecret)
                    .Build();  

This document implements a single confidential client application.


Solution

  • You can specify a different tenant id when acquiring a token.

    This should work:

    var app = ConfidentialClientApplicationBuilder.Create("client-id")
        .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs)
        .WithClientSecret("secret")
        .Build();
    
    var result = await app.AcquireTokenForClient(new[]{"https://graph.microsoft.com/.default"})
        .WithAuthority(AzureCloudInstance.AzurePublic, Guid.Parse("target-tenant-id"))
        .ExecuteAsync();
    

    So we specify "organizations" as the app authority, but then specify a specific tenant when acquiring a token.