如何在.Net Core 6 API内部调用Azure REST API

omqzjyyz  于 2023-03-13  发布在  .NET
关注(0)|答案(1)|浏览(136)

我有一个服务主体,它可以访问我的组织中的所有租户及其资源。client_id client_secret and tenant_id.Net Core 6 API中使用,以下函数用于获取该服务主体的访问令牌:

public string getAccessToken(string tenantID)
        {
            var _config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            var scopes = new string[] { _config["Azure:vm-executer:scope"]! };

            var confidentialClientApplication = ConfidentialClientApplicationBuilder
             .Create(_config["Azure:vm-executer:client_id"])
             .WithTenantId(tenantID)
             .WithClientSecret(_config["Azure:vm-executer:client_secret"])
             .WithAuthority($"https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token")
             .Build();

            var result = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

            return result.Result.AccessToken;
        }

我 * 成功 * 使用该访问令牌向Azure REST API发出请求,以
1.使用https://management.azure.com/subscriptions?api-version=2020-01-01列出订阅
1.列出具有https://management.azure.com/subscriptions/{subscriptionID}/providers/Microsoft.Compute/virtualMachines?api-version=2022-11-01的虚拟机
我在《 Postman 》里做了这些,效果真的很好!
但是,现在我想从我的.Net 6 API内部执行。

我的目标是明确地返回 Postman 给我的特定请求的响应。因此,例如,当我想要列出订阅时,它应该具有 Postman 的相同响应,如下所示:

到目前为止,我已经使用RestClient实现了这个功能,但我卡住了,需要帮助。

public SubscriptionResource getSubscriptionID(string accessToken)
        {
            var uri = "https://management.azure.com/subscriptions?api-version=2020-01-01";
            var client = new RestClient();
            var request = new RestRequest(uri, Method.Get);
            request.AddHeader("Authorization", $"Bearer {accessToken}");
            RestResponse response = client.Execute(request);

            return response;
        }

我已经阅读了关于Azure SDK for .net的信息,并尝试使用Azure.ResourceManager包,但没有成功。

watbbzwu

watbbzwu1#

我尝试在我的环境中重现相同的结果,结果如下:

我使用下面的C#代码,并在response中成功地获得了订阅列表的访问令牌,如下所示:

using System.Net.Http.Headers;
using Microsoft.Identity.Client;

namespace AzureRestApiListSub
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();

        static async Task Main(string[] args)
        {
            // Azure AD application details
            string clientId = "bb2c371a-d0f8-492c-9252-xxxxxxxxxxxx";
            string clientSecret = "xxxxxxxxxxxxxxxxxxxxxx";
            string tenantId = "2f6e32f4-8752-4f56-9154-xxxxxxxxxxxxx";

            // Azure REST API endpoint
            string apiVersion = "2020-01-01";
            string endpoint = $"https://management.azure.com/subscriptions?api-version={apiVersion}";

            {
                // Set up the authentication context
                var confidentialClientApplication = ConfidentialClientApplicationBuilder
                    .Create(clientId)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                    .Build();

                string[] scopes = new string[] { "https://management.azure.com/.default" };

                // Authenticate and acquire an access token
                var authResult = await confidentialClientApplication
                    .AcquireTokenForClient(scopes)
                    .ExecuteAsync();

                string accessToken = authResult.AccessToken;
                Console.WriteLine(accessToken);
                Console.WriteLine();

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                HttpResponseMessage response = await client.GetAsync("https://management.azure.com/subscriptions?api-version=2021-01-01");
                string json = await response.Content.ReadAsStringAsync();
                Console.Write(json);
                Console.WriteLine();
            }
        }
    }  
}

答复:

为了确认这一点,我在Postman中使用了上述访问令牌,并得到了如下相同的结果:

GET https://management.azure.com/subscriptions?api-version=2020-01-01

答复:

相关问题