How to manage access token via MSAL and a WebAPI as a background of a WebApp

Adrien Ruffie 1 Reputation point
2022-12-30T13:03:50.7+00:00

Dear all,

we use in our webapp, we have and endpoint in a WebAPI which use a signed user which provide an authorization code for generating an access/refresh token, via an HttpClient request to:

https://login.microsoftonline.com/{tenandid}/oauth2/v2.0/authorize?scope=user.read calendars.readwrite calendars.readwrite.shared offline_access openid

we want to use MSAL, but I recently found with the following method:
AuthenticationResult result = ConfidentialClientApp.AcquireTokenByAuthorizationCode(scopes, authorizationCode);

its no longer return a refresh token du to caching access token of MSAL.

I can use the cache to renew the access token when is expired with:
result = ConfidentialClientApp.AcquireTokenSilent(ServiceConstants.ALL_SCOPE_AUTHORIZATIONS.Split(' '), account).ExecuteAsync();

But I found this text in Microsoft documentation:
--> We don't recommend it in production if you request user tokens (AcquireTokenByAuthorizationCode, AcquireTokenSilent, AcquireTokenOnBehalfOf).

On this page:
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization?tabs=aspnet#in-memory-token-cache-1

Part: In-memory token cache

Consequently how we can manage the access token renew in our architecture ? For refresh an expired access token ? Because is not recommended in production to use AcquireTokenByAuthorizationCode.

Thank a lot and best regards

Adrien

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,664 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Shweta Mathur 27,936 Reputation points Microsoft Employee
    2023-01-05T13:02:03.47+00:00

    Hi @Adrien Ruffie ,

    Thanks for reaching out and apologies for delay in response.

    Your understanding is correct here. In-memory caches are good for applications that don't require tokens to persist between app restarts which is mainly for local app development.

    As mentioned in the link provided by you, AcquireTokenByAuthorizationCode() require user interaction to get the access token. So, to persist the user details is not recommended using in memory cache.

    For token persistence, MSAL provides and recommended to use distributed token cache (Redis, SQL Server, Azure Cosmos DB, distributed memory) to request tokens for users in a production application.

    A distributed memory cache will not clear when the app stops. In this case, the cached items are stored by the app instance on the server where app is running.

    Hope this will help.

    Thanks,
    Shweta


    Please remember to "Accept Answer" if answer helped you.