Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 439
pranav daipuria Avatar asked Dec 09 '25 21:12

pranav daipuria


1 Answers

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();
like image 126
Joey Cai Avatar answered Dec 12 '25 09:12

Joey Cai