I am developing a .NET web-app that should authorize to multiple azure resources via Managed Identities. Is it best practice to create a new DefaultAzureCredential()
for each single service to which my app should authorize, or use a single Credentials-Instance for all services?
// pseudocode: each service has its own AzureCredentials
var blobs = new BlobServiceClient(new Uri("mycontainer.url..."), new DefaultAzureCredential());
var eventHubClient = new EventHubProducerClient("eventhub.servicebus.windows.net", new DefaultAzureCredential());
var postgresScope = new TokenRequestContext(scopes: new string[] { "https://ossrdbms-aad.database.windows.net/.default" });
var postgresToken = await new DefaultAzureCredential().GetTokenAsync(tokenScope, cancellationToken);
// pseudocode: single AzureCredentials for all services
var credentals = new DefaultAzureCredential();
var blobs = new BlobServiceClient(new Uri("mycontainer.url..."), credentails);
var eventHubClient = new EventHubProducerClient("eventhub.servicebus.windows.net", credentials);
var postgresScope = new TokenRequestContext(scopes: new string[] { "https://ossrdbms-aad.database.windows.net/.default" });
var postgresToken = await credentals .GetTokenAsync(tokenScope, cancellationToken);
If you believe all services will always use the same kind of credentials and there's no plan to diversify the authentication strategies for different services, a single instance might be more appropriate for code clarity and a tiny bit of memory savings.
If there's a possibility that services might have diversified authentication needs in the future, having separate instances can offer more flexibility.
In practice, the memory overhead of creating multiple DefaultAzureCredential instances is negligible for most applications. So, if in doubt, choosing the more flexible approach (multiple instances) might be a safer bet.