简体   繁体   中英

Get Access Token for Azure

I am trying to access the Azure access token to get some information related to APIs hosted in Azure.

I used the code below in Visual studio and I get the token since I logged into VS with my credentials.

However, when I deployed this code I don't get the token and it throws an error, since the deployed environment does not have VS and just has the executable running there.

Sample code:

 AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/", "tenantId").Result;

What is the best practice to get the azure access token?

Here is the code that worked for me

var tenantId = "<Your Tenant ID>";
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var token = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com", tenantId);
var tokenCredentials = new TokenCredentials(token);
var azure = Azure
    .Configure()
    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
    .Authenticate(new AzureCredentials(
        tokenCredentials,
        tokenCredentials,
        tenantId,
        AzureEnvironment.AzureGlobalCloud))
    .WithDefaultSubscription();

Note : Make sure you install Microsoft.Rest.ClientRuntime for "TokenCredentials".

REFERENCES: Using AzureServiceTokenProvider to authenticate with the Azure Libraries for .NET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM