【问题标题】:Using Azure resource graph with .net SDK将 Azure 资源图与 .net SDK 结合使用
【发布时间】:2020-05-05 23:47:13
【问题描述】:
我正在尝试使用带有 Azure .NET SDK 的 Azure Resource Graph 来查询我的 Azure 资源管理器资源。目前我坚持创建ResourceGraphClient,我不确定要为System.Net.Http.DelegatingHandler[] 参数提供什么值。
【问题讨论】:
标签:
.net
azure
azure-resource-manager
azure-sdk-.net
【解决方案1】:
根据我的研究,如果你想直接创建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);
}