问题
I'm trying to query my Azure Resource Manager resources using Azure Resource Graph with Azure .NET SDK. Currently I'm stuck at creating a ResourceGraphClient
, I'm not really sure what value to provide to the System.Net.Http.DelegatingHandler[]
parameter.
回答1:
According to my research, If you want to create ResourceGraphClient
with System.Net.Http.DelegatingHandler[]
directly, it is impossible. Because it is a projected
Constructor. For more details, please refer to here
Besides, according to my test, we can create a ResourceGraphClient
with ServiceClientCredentials
class.
For example 1. Create a service principal
az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth
- code
public async static Task Test() {
CustomLoginCredentials creds = new CustomLoginCredentials();
var resourceGraphClient = new ResourceGraphClient(creds);
var queryReq = new QueryRequest {
Subscriptions = new List<string> { "<your subscription id>" },
Query = "where type == 'microsoft.web/sites'"
};
var result = await resourceGraphClient.ResourcesAsync(queryReq);
Console.WriteLine(result.Count);
}
class CustomLoginCredentials : ServiceClientCredentials {
private static string tenantId = "<your sp tenant id>";
private static string clientId = "your sp app id";
private static string cert = "your sp password";
private string AuthenticationToken { get; set; }
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
var authenticationContext =
new AuthenticationContext("https://login.windows.net/"+tenantId);
var credential = new ClientCredential(clientId: clientId, clientSecret: cert);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/",
clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
AuthenticationToken = result.AccessToken;
}
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (AuthenticationToken == null)
{
throw new InvalidOperationException("Token Provider Cannot Be Null");
}
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
await base.ProcessHttpRequestAsync(request, cancellationToken);
}
来源:https://stackoverflow.com/questions/59815299/using-azure-resource-graph-with-net-sdk