5

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

Dzior
  • 1,485
  • 1
  • 14
  • 30

2 Answers2

4

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();
Dzior
  • 1,485
  • 1
  • 14
  • 30
0

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.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • I'm not sure this will help me, as this seems to be another workflow. I will explain details in edit – Dzior Jan 14 '19 at 10:08
  • See the section “Running the application using a Service Principal” in the linked doc got how to use a client Id and client secret. – David Browne - Microsoft Jan 14 '19 at 13:46
  • There is a specific comment saying: "This applies only to local development. When your solution is deployed to Azure, the library switches to a managed identity for authentication." – Dzior Jan 17 '19 at 12:15