将Azure资源图与.net SDK结合使用
我正在尝试使用带有Azure .NET SDK的Azure资源图查询我的Azure资源管理器资源.目前,我一直在创建ResourceGraphClient
,但我不确定如何为System.Net.Http.DelegatingHandler[]
参数提供什么值.
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.
根据我的研究,如果要直接使用System.Net.Http.DelegatingHandler[]
创建ResourceGraphClient
,则不可能.因为它是projected
构造函数.有关更多详细信息,请参阅
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
此外,根据我的测试,我们可以使用ServiceClientCredentials
类创建一个ResourceGraphClient
.
Besides, according to my test, we can create a ResourceGraphClient
with ServiceClientCredentials
class.
例如 1. 创建服务主体
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);
}