通过.net SDK使用Azure资源图

问题描述 投票:0回答:1

我正在尝试使用带有Azure .NET SDK的Azure资源图查询我的Azure资源管理器资源。目前,我一直坚持创建ResourceGraphClient,我不确定是否要为System.Net.Http.DelegatingHandler[]参数提供什么值。

.net azure azure-resource-manager azure-sdk-.net
1个回答
0
投票

根据我的研究,如果要直接用ResourceGraphClient创建System.Net.Http.DelegatingHandler[],则不可能。因为它是projected构造函数。有关更多详细信息,请参阅hereenter image description here

此外,根据我的测试,我们可以使用ResourceGraphClient类创建一个ServiceClientCredentials

例如1. Create a service principal

az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth
  1. 代码
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);

        }

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.