DefaultAzureCredential is the recommended approach for authenticating with Azure services,
and in most cases, we rarely rely on access keys anymore, authentication is
typically handled through managed identities.
However, during local development, when authentication falls back to the
developer’s user account, this can occasionally introduce unexpected
complexity and frustration.
I usually use the following DefaultAzureCredentialOptions:
I usually use the following DefaultAzureCredentialOptions:
DefaultAzureCredentialOptions credentialOptions = new()
{
// Explicitly specify the tenant to avoid cross-tenant issues
TenantId = "<TenantId>",
// Prioritize local development credentials
ExcludeAzureCliCredential = false, // Azure CLI (az login)
ExcludeAzureDeveloperCliCredential = false, // Azure Developer CLI (azd auth login)
ExcludeVisualStudioCredential = true,
// Exclude irrelevant credentials
ExcludeInteractiveBrowserCredential = true,
ExcludeWorkloadIdentityCredential = true,
// Keep managed identity for production.
ExcludeManagedIdentityCredential = false,
};
DefaultAzureCredential defaultAzureCredential = new(credentialOptions);
Key points:
- Always specify TenantId to avoid cross-tenant issues
- Always avoiding exclude VisualStudioCredential, and relying on Azure CLI and Azure Developer CLI credentials
- Keep ManagedIdentityCredential enabled so the same code works in production
If you want to enable logging for any troubleshooting:
using Azure.Core.Diagnostics;
using System.Diagnostics.Tracing;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Add services to the container.
WebApplication app = builder.Build();
ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
ILogger azureIdentityLogger = loggerFactory.CreateLogger("Azure.Identity");
using var listener = new AzureEventSourceListener((args, message) =>
{
if (args.EventSource.Name == "Azure-Identity")
{
azureIdentityLogger.LogInformation("{Message}", message);
}
}, EventLevel.Verbose);
// Configure the HTTP request pipeline.app.Run()
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment