Jai
Jai

Reputation: 466

Azure ExpiredAuthenticationToken when fetching the Azure data Factory information by C# console application via Visual Studio

I have written a console application which could fetch all information about Azure datafactory for a given azure subscription and resource group. I am using Microsoft provided .NET API. The code runs for a while as it monitors all the data factories and pipelines and put it into azure SQL database. I am getting following exception when code runs for more than a hour: token expire exception

I am using following code to generate the to

 public static async Task<string> GetAuthorizationHeader ()
        {
        AuthenticationContext context = new AuthenticationContext(ConfigurationManager.AppSettings["ActiveDirectoryEndpoint"] +
            ConfigurationManager.AppSettings["ActiveDirectoryTenantId"]);
        ClientCredential credential = new ClientCredential(
            ConfigurationManager.AppSettings["ApplicationId"],
            ConfigurationManager.AppSettings["Password"]);
        AuthenticationResult result = await context.AcquireTokenAsync(
            resource: ConfigurationManager.AppSettings["WindowsManagementUri"],
            clientCredential: credential);

        if ( result != null )
            return result.AccessToken;

        throw new InvalidOperationException("Failed to acquire token");
        }

public static TokenCloudCredentials GetTokenCloudCredentials ()
        {
        return new TokenCloudCredentials(ConfigurationManager.AppSettings["SubscriptionId"],
            GetAuthorizationHeader().Result);
        }

This code is available at microsoft website here.

Is there any way to increase the expiration time of token? or How do I refresh the authentication token?

Thanks, Jai

Upvotes: 0

Views: 3205

Answers (2)

byte
byte

Reputation: 1685

As the error indicates, your token has expired. The token lifetimes are configured with your Token Service / Identity Provider (e.g. Azure AD). The token time can be changed but please consider the security aspects when issuing long lived tokens (and look for best practices around token lifetime if you decide to update this).

I believe, instead of further increasing the token lifetime, you could consider refreshing the token before it expires (or request for a new token after expiry) based on your use case.

Before you invoke the Api, Please check for the token expiry time with current time and refresh / request the token. This will help avoid a call to the service with an expired token.

Upvotes: 1

Martin Esteban Zurita
Martin Esteban Zurita

Reputation: 3209

I had a similar problem but with data factory version 2, I fixed it by capturing the exception with a try catch, and in the catch part call the same method to obtain the token.

I'm not sure if it will work on version 1, but it should!

Hope this helped

Upvotes: 0

Related Questions