我正在尝试使用带有Azure .NET SDK的Azure资源图查询我的Azure资源管理器资源。目前,我一直坚持创建ResourceGraphClient
,我不确定是否要为System.Net.Http.DelegatingHandler[]
参数提供什么值。
根据我的研究,如果要直接用ResourceGraphClient
创建System.Net.Http.DelegatingHandler[]
,则不可能。因为它是projected
构造函数。有关更多详细信息,请参阅here
此外,根据我的测试,我们可以使用ResourceGraphClient
类创建一个ServiceClientCredentials
。
例如1. Create a service principal
az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth
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);
}