pranav daipuria
pranav daipuria

Reputation: 57

How to get refresh token in MSAL .Net C#

I have identified two approaches for acquiring token in MSAL for EWS

  1. Using Username Password approach.
  2. Using Daemon Confidential approach.

In both above approached after I acquire token, I am not able to refresh it. Though I tried to follow MS docs but no success. GetAccountsAsync() always gives empty result.

Here is my Code for Username Password approach

var publicClientApplication = PublicClientApplicationBuilder.Create(ClientId)
                 .WithAuthority(AzureCloudInstance.AzurePublic, TenantId).Build();
var accounts = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult();
var result = publicClientApplication
                 .AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                 .ExecuteAsync().GetAwaiter().GetResult();

Can anyone guide me why it is happening so, or is there doc explaining this flow.

Upvotes: 3

Views: 10479

Answers (1)

Joey Cai
Joey Cai

Reputation: 20067

MSAL maintains a token cache and caches a token after it has been acquired. It's also capable of refreshing a token when it's getting close to expiration (as the token cache also contains a refresh token).

MSAL.NET does not expose refresh tokens, for security reasons: MSAL handles refreshing tokens for you with token cache.

As you GetAccountsAsync() always get empty, did your Token Cache serialization.

By default, access tokens expire after 1h, and if AAD is busy when the tokens expire, your application will become unavailable because you cannot acquire a valid access token. You can improve the availability of your application by regularly forcing a refresh. We recommend to force a refresh every 30 min, or half the lifetime of the AT when this is a custom lifetime.

result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
             .WithForceRefresh(true)
             .ExecuteAsync();

Upvotes: 6

Related Questions