How to obtain bearer token for azure service principal with C#

Viewed 4512

I need to get the bearer access token for service principal. I want to use it in C# application.

Given that I have principial Id and secret and tenant id, how can I obtain it?

EDIT: to be more specific: I have service principal with client_id and client_secret. I can obtain the bearer token by azure cli using following commands

az login --service-principal -u client_id --tenant my_tenant_domain -p client_secret
az account set --subscription my_subscription_id
az account get-access-token

I would like to get the same token without using CLI, that is using Azure SDK for dot net or rest call

2 Answers

I ended up with following code:

var adSettings = new ActiveDirectoryServiceSettings
{
    AuthenticationEndpoint = new Uri(AzureEnvironment.AzureGlobalCloud.AuthenticationEndpoint),
    TokenAudience = new Uri(AzureEnvironment.AzureGlobalCloud.ManagementEndpoint),
    ValidateAuthority = true
};

await ApplicationTokenProvider.LoginSilentAsync(
                TenantId.Value,
                ServicePrincipalId,
                ServicePrincipalSecret,
                    adSettings,
                    TokenCache.DefaultShared);

var token = TokenCache.DefaultShared.ReadItems()
    .Where(t => t.ClientId == ServicePrincipalId)
    .OrderByDescending(t => t.ExpiresOn)
    .First();
Related