'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 1:[1]

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

Solution 2:[2]

To acquire a token credential for your code to approve calls to Microsoft Graph, one workaround is to utilize the ChainedTokenCredential, ManagedIdentityCredential and EnvironmentCredential classes.

The following snippet generates the authenticated token credential and implements those to the creation of a service client object.

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;
    }));

REFERENCES:

  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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wuz
Solution 2 SwethaKandikonda-MT