Monday 29 May 2023

Call Azure API using Bearer acess token

using System;

using System.Drawing;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using System.Web;

using Azure.Identity;

using Azure.Core;

using Nancy.Json;

using Newtonsoft.Json;

 

namespace AzCallAzureApi

{

    internal class Program1

    {

        static async Task Main()

        {

            try

            {

                // get the access first token first.

                string token = await GetAccessToken("TenantID", "ClientID", "ClientSecret");

                // get the API and process the result

                await GetResults(token);

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Exception: {ex.Message}");

            }

        }

 

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)

        {

            Console.WriteLine("Begin GetAccessToken");

 

            var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);

            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), CancellationToken.None);

            return result.Token;

        }

 

        // Set authorization and call the required api method

        private static async Task<string> GetResults(string token)

        {

            var httpClient = new HttpClient

            {

                BaseAddress = new Uri("https://management.azure.com/subscriptions/")

            };

            string URI = "Your URI";

            httpClient.DefaultRequestHeaders.Remove("Authorization");

            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            HttpResponseMessage response = await httpClient.GetAsync(URI);

            if (response.IsSuccessStatusCode)

            {

                var HttpsResponse = await response.Content.ReadAsStringAsync();

                var JSONObject = JsonConvert.DeserializeObject<object>(HttpsResponse);

            Console.WriteLine(JSONObject);

            var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>((string)JSONObject);

            return response.StatusCode.ToString();

            }

            return string.Empty;

        }  

    }

}

 


No comments:

Post a Comment