使用 Azure Function .NET 和用户管理的标识进行资源图查询?

Resource Graph query using Azure Function .NET and User managed Identity?

example 中,DotNet-ResourceGraphClient 需要 ServiceClientCredentials。我不知道如何直接使用用户分配的托管身份。 例如:

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = umiClientId }); 
ResourceGraphClient argClient = new ResourceGraphClient(serviceClientCreds);
results in: Argument 1: cannot convert from 'Azure.Identity.DefaultAzureCredential' to 'Microsoft.Rest.ServiceClientCredentials'.

我找到了一个 PHP-example,凭据 = MSIAuthentication()。任何人都可以为 dotnet-azure-resource-graph-sdk 提供类似的例子吗? 谢谢

要为您的代码获取令牌凭据以批准对 Microsoft Graph 的调用,一种解决方法是利用 ChainedTokenCredentialManagedIdentityCredential环境证书 类.

以下代码片段生成经过身份验证的令牌凭据并将其实现以创建服务客户端对象。

var credential = new ChainedTokenCredential(
    new ManagedIdentityCredential(),
    new EnvironmentCredential());
var token = credential.GetToken(
    new Azure.Core.TokenRequestContext(
        new[] { "https://graph.microsoft.com/.default" }));

var accessToken = token.Token;
var graphServiceClient = new GraphServiceClient(
    new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage
        .Headers
        .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

        return Task.CompletedTask;
    }));

参考资料:

  1. Access Microsoft Graph from a secured .NET app as the app
  2. Tutorial: Access Microsoft Graph from a secured .NET app as the app

感谢您的投入。 使用用户管理的标识进行身份验证。 https://docs.microsoft.com/en-us/dotnet/api/overview/azure/service-to-service-authentication#connection-string-support

log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
// Connect client with user assigned managed identity.
string umiClientId = "<your-user-assigned-managed-identity-client-id>";
string conStrOpts = string.Format("RunAs=App;AppId={0}", umiClientId);
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(
                    conStrOpts
                );
var tokenCredentials = new TokenCredentials(
                        await azureServiceTokenProvider
                        .GetAccessTokenAsync("https://management.azure.com/")
                        .ConfigureAwait(false)
                );
ResourceGraphClient argClient = new ResourceGraphClient(tokenCredentials);