Hi @Augusto Piva Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.
There are different ways you can get the token through the code. Please find the below few options through which you can achieve them
Approach 1: Through C# code invoking Azure CLI command.
using System.Diagnostics;
using System;
namespace AccessToken // Note: actual namespace depends on the project name.
{
internal class Program
{
static async Task Main(string[] args)
{
string resource = "https://apps.azureiotcentral.com";
string command = $"az account get-access-token --resource {resource}";
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c {command}",
RedirectStandardOutput = true,
UseShellExecute = false
};
Process process = new Process
{
StartInfo = startInfo
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
string token = output.TrimEnd();
Console.WriteLine(token);
}
}
}
The above code needs the Azure CLI to be installed on the machine where your application is hosted, and it will utilize the user credentials logged into the Azure CLI command line to fetch the credentials.
Approach 2: Use Azure Active Directory Client ID and Client Secret authentication to get the bearer token.
For this approach to work, you would need to do the following to get the client ID and clinet secret details for the code Create an Azure AD Application:
- Go to the Azure portal.
- Navigate to your Azure Active Directory.
- Click on "App registrations" in the left-hand menu.
- Click on the "+ New registration" button.
- Fill in the necessary information for your application.
Generate a Client Secret:
- After creating the application, go to the "Certificates & secrets" section.
- Under the "Client secrets" section, click on "+ New client secret."
- Enter a description for the secret and choose an expiration period.
- Click the "Add" button.
Copy the Client Secret:
- After you've added the client secret, a new secret value will be generated. Copy this value immediately, as you won't be able to see it again.
- Replace the placeholder in your code with the actual client secret you generated.
Copy the Client ID:
- After creating the application, you will see a page with your application's details.
- The "Application (client) ID" listed on this page is the Client ID you need for your code.
- Copy the Client ID and use it in your code.
Please find the code below to use this approach.
using System;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Identity.Client;
namespace AccessToken // Note: actual namespace depends on the project name.
{
internal class Program
{
static async Task Main(string[] args)
{
string clientId = "<ClientID>";
string clientSecret = "<ClinetSecret>";
string tenantId = "<TenantID>";
string subscriptionId = "<Subscription>";
// Get an access token
resource = "https://apps.azureiotcentral.com/.default";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var result = await app.AcquireTokenForClient(new[] { resource }).ExecuteAsync();
Console.WriteLine("Second approach result is "+result.AccessToken);
}
}
}
Please also make sure to provide Tenant ID which can be obtained from Azure Active Directory and your Subscription ID details.
Approach 3: Getting Access token through Python code
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
credential = DefaultAzureCredential()
subscription_id = "<SubscriptionID>"
resource_client = ResourceManagementClient(credential, subscription_id)
access_token = credential.get_token("https://apps.azureiotcentral.com").token
print('Access token is '+access_token)
The Python code would just need the subscription ID. You can look into the .Net SDK and perhaps find a similar implementation in C#.
Hope this helps. Please let me us know if you have any additional questions or need further assistance.
If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.