1

I have the following simple .NET script:

static void Main(string[] args)
{
    var result1 = Login().Result;
    var result2 = Login().Result;
}

public static async Task<AuthenticationResult> Login()
{
    var options = new PublicClientApplicationOptions();
    options.TenantId = "...";
    options.ClientId = "...";

    var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                    .WithDefaultRedirectUri()
                    .Build();

    AuthenticationResult result;
    var accounts = await app.GetAccountsAsync();
    IAccount account = accounts.FirstOrDefault();
    var scopes = new string[] { "..." };
    try
    {
        result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();
    }
    catch (MsalUiRequiredException)
    {
        result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
    }
    return result;
}

My expectation would be that the first Login(...) call executes the interactive authentication, then the second call var accounts = await app.GetAccountsAsync() returns the previously logged in account. However, the accounts does not have any item. So, it seems that the token cache is not part of these calls.

Is there any way to store the logged in account in the first call? Should not be the automatic?

Tibor Takács
  • 3,535
  • 1
  • 20
  • 23

1 Answers1

1

I had the same issue and after spelunking around the MSAL library with ilspy I discovered that the cache is stored on the IPublicClientApplication app it self.

So if you reuse the app, you will get advantage of the cache as well.

alyx
  • 540
  • 1
  • 6
  • 8
  • Is it possible to use the central, permanent token cache storage somehow? – Tibor Takács Aug 03 '20 at 18:56
  • The default token cache is in memory only. If you want to commit it and re-use the cache after application restart for example, see the MSAL example for a token cache helper, https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization#simple-token-cache-serialization-msal-only – alyx Aug 04 '20 at 06:27