How to get Azure Access Token using C#

This is part 4 of the series Create Azure Resource Manager Bot“.

Representational State Transfer (REST) APIs are service endpoints that support sets of HTTP operations (methods), which provide create, retrieve, update, or delete access to the service’s resources.

For more information. Refer Microsoft Documentation.

Pre-requisites

  1. Visual Studio
  2. Service Principal in Azure – To know how to create service principal, go through my post on Creating Service Principal using PowerShell.

Getting Access Token using C#

Launch Visual Studio. Select a Console App (.NET Core) Project. Give the project name and create the project.

For communicating with Azure Active Directory, we need libraries. Right click on Dependencies -> Click Manage Nuget Packages.

Browse for “Microsoft.IdentityModel.Clients.ActiveDirectory” package and install the latest version.

Import the library in Program.cs file.

using Microsoft.IdentityModel.Clients.ActiveDirectory;

Add a new method GetAuthorizationToken() in Program.cs file.

public static void GetAuthorizationToken()
        {
            ClientCredential cc = new ClientCredential(AzureDetails.ClientID, AzureDetails.ClientSecret);
            var context = new AuthenticationContext("https://login.microsoftonline.com/" + AzureDetails.TenantID);
            var result = context.AcquireTokenAsync("https://management.azure.com/", cc);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the Access token");
            }
            AzureDetails.AccessToken = result.Result.AccessToken;
        }

Create a new class file with name AzureDetails and declare the following fields.

public static string ClientID = "<Client ID or App ID>";
        public static string ClientSecret = "<Client Secret or Password>";
        public static string TenantID = "<Tenant ID>";
        public static string AccessToken { get; set; }

Remember, never keep your credentials or configuration details in code. You can use Azure vault or appsettings.json file. For demo purpose I am hard-coding these values.

Add your configuration details in ClientID, ClientSecret and TenantID fields.

Call the method GetAuthorizationToken() in Main() and print the Access Token on console output.

static void Main(string[] args)
        {
            GetAuthorizationToken();
            Console.WriteLine(AzureDetails.AccessToken);
        }

Below is the console output with access token.

Source code of above demo is available in Downloads Page and GitHub.

Thank you All!!! Hope you find this useful.

If you liked our content and it was helpful, you can buy us a coffee or a pizza. Thank you so much.


One thought on “How to get Azure Access Token using C#

Add yours

Up ↑

%d bloggers like this: