Dzior
Dzior

Reputation: 1495

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

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

Upvotes: 5

Views: 7059

Answers (2)

Dzior
Dzior

Reputation: 1495

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();

Upvotes: 4

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89141

The current and best way is to use the Microsoft.Azure.Services.AppAuthentication package, as it supports Managed Service Identities, as well as Service Prinicpals.

See, for instance, Service-to-service authentication to Azure Key Vault using .NET . For other services you can follow the same process, changing the requested resource from https://management.azure.com/, as appropriate.

Upvotes: 0

Related Questions