Azure AD login using C#. Acquiring Refresh token and Access token

Viewed 2992

Task: I need to create a WPF application, which will work with EWS(Exchange web-service). I, also, have the 2 restrictions:

  • login should proceed only once (it should use refresh token to reconnect)
  • it should support 2FA

My solution part: I use OAuth to connect to Azure AD. As OAuth client I use Microsoft.Identity.Client. For the first login I have such code:

var pcaOptions = new PublicClientApplicationOptions
{
    ClientId = *my_client_id*,
    TenantId = *my_tenant*
};
AuthenticationResult authResult = pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync().Result;

This part of code shows up a WPF window, where I input credentials and return me a result(AuthenticationResult), which contains Access Token.

Problem: AuthenticationResult doesn't have a Refresh Token, so I can't fulfill the first restriction. Are there any solutions or over ways?

Additional question: How to update a Refresh token using Microsoft.Identity.Client?

1 Answers

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

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).

You can improve the availability of your application by regularly using WithForceRefresh which will internally acquire new access token when set to true

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