Skip to content

AcquireTokenSilentAsync using a cached token

Jean-Marc Prieur edited this page Mar 6, 2018 · 23 revisions

Token are cached

Once MSAL.NET has acquired a token for a user for a Web API, it caches it. Next time the application wants a token, it should first call AcquireTokenSilentAsync to verify if an acceptable token is in the cache, and if not, call AcquireTokenAsync.

AcquireTokenAsync don't get token from the cache

Contrary to what happens in ADAL.NET, the design of MSAL.NET is such that AcquireTokenAsync never looks at the cache. This is your responsibility as an application developer to call AcquireTokenSilentAsync first.

Recommended call pattern

The recommanded call pattern is to first try to call AcquireTokenSilentAsync, and if it fails with a MsalUiRequiredException, call AcquireTokenAsync

AuthenticationResult result = null;
try
{
    result = await app.AcquireTokenSilentAsync(scopes, app.Users.FirstOrDefault());
}
catch (MsalUiRequiredException ex)
{
    // A MsalUiRequiredException happened on AcquireTokenSilentAsync. 
    // This indicates you need to call AcquireTokenAsync to acquire a token
    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

    try
    {
        result = await app.AcquireTokenAsync(scopes);
    }
    catch (MsalException msalex)
    {
        ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
    }
}
catch (Exception ex)
{
    ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
    return;
}

if (result != null)
{
    string accessToken = result.AccessToken;
    // Use the token
}

For the code in context, please see the active-directory-dotnet-desktop-msgraph-v2 sample

Getting started with MSAL.NET

Acquiring tokens

Desktop/Mobile apps

Web Apps / Web APIs / daemon apps

Advanced topics

News

FAQ

Other resources

Clone this wiki locally