排查 DefaultAzureCredential:确定使用的凭据

发布: (2025年12月10日 GMT+8 22:09)
2 min read
原文: Dev.to

Source: Dev.to

问题描述

在使用 Azure Identity NuGet 包时,DefaultAzureCredential 会尝试加载一系列凭据类型,例如环境变量、Visual Studio、Azure 托管身份等。完整的凭据列表已在 Azure 文档中列出:

https://learn.microsoft.com/en-us/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet

除非手动启用日志,否则很难确定到底使用了哪些凭据。Microsoft 推荐的做法会产生非常冗长的输出。为简化输出,可在应用程序的启动代码中加入以下片段。

using var listener = new AzureEventSourceListener((e, message) =>
{
    if (e.EventSource.Name == "Azure-Identity")
    {
        Console.WriteLine(message);
        // Alternatively, use _logger.LogInformation() if running in Azure
        // WARNING: These logs may include sensitive credentials
        // depending on the options selected below
    }
},
System.Diagnostics.Tracing.EventLevel.LogAlways);

DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions
{
    Diagnostics =
    {
        IsAccountIdentifierLoggingEnabled = true,
        // Useful extra options for debugging
        // These act as a whitelist of fields to log.
        // LoggedHeaderNames = { "x-ms-request-id" },
        // LoggedQueryParameters = { "api-version" },
        // This enables logging the request or response body
        // IsLoggingContentEnabled = true
    }
};

AzureEventSourceListener 会创建一个详细的日志记录器。添加上述过滤器后可以去除大量噪声。

你应该会看到类似以下的输出:

EnvironmentCredential.GetToken invoked
EnvironmentCredential.GetToken was unable to retrieve an access token
...
VisualStudioCredential.GetToken succeeded

这些输出可以直观地帮助你确定到底是哪种凭据成功(或失败)了。

Azure Identity 日志记录

https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md#logging

相关问题

https://github.com/Azure/azure-sdk-for-net/issues/27872

Back to Blog

相关文章

阅读更多 »

掌握在 .NET 中使用 NuGet 包

NuGet到底是什么?想象一下,NuGet是 .NET 版的 Amazon 或 Mercado Libre。你不会自己制造家具的每一颗螺丝,而是向商店购买它们。- Package...