Tuesday, March 29, 2022

Azure @ Enterprise - How to cache JWT access token in MSAL.Net?

When we start using the MSAL.Net library to work with Azure Active Directory and experience its fluency and other features, we start thinking that has everything we need. If we take the simple example of obtaining a JWT access token, we naturally think that the library is caching the token based on the "exp" attribute. At least I came to multiple scenarios where developers thought, the library is caching access tokens but in reality it is not.

How to cache the JWT access tokens in MSAL.Net?

It is not easy and it is not the way we developers normally think a library will offer. 

First of all, we have to write code to get token from the cache. No, it won't return a null or empty string if the token is not present. Instead, it throws an exception. We have to catch that exception and acquire a token that the cache will intercept and update.
  • Try to get token from the cache using AcquireTokenSilent()
  • If it throws an exception try to get a token using other AcquireToken methods based on our authentication model.
This is not a workaround. It is the documented solution.

No comments: