Search code examples
azureauthentication.net-coreazure-resource-graph

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


In the example the DotNet-ResourceGraphClient requires ServiceClientCredentials. I do not know how to use a user-assigned-managed-identity directly. For instance:

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'.

I found a PHP-example with credentials = MSIAuthentication(). Can anyone provide a similar example for dotnet-azure-resource-graph-sdk? Thanks


Solution

  • thanks for the input. Authentication with user managed identity. https://learn.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);