[Feature Request] Easier token caching
See original GitHub issueIs your feature request related to a problem? Please describe. Token caching is hard, because it involves writing a lot of boiler plate code and because of bad initial design, where a notification mechanism was used instead of an object / interface.
Microsoft.Identity.Web simplifies things this by introducing MsalAbstractTokenCacheProvider
which deals with the complex Before
/ After
notifications and focuses on Read
/ Write
operations:
WriteCacheBytesAsync(string cacheKey, byte[] bytes);
Task<byte[]> ReadCacheBytesAsync(string cacheKey);
Solution 1
Introduce MsalAbstractTokenCacheProvider
in MSAL.
IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder
.Create("id")
.WithClientSecret("secret")
.Build();
// L1TokenCache can live in MSAL
MsalAbstractTokenCacheProvider adapter = new L1TokenCache(MaxSize = "2Gb");
adapter.Init(cca.AppTokenCache);
// OR RedisTokenCacheAdapter lives in Microsoft.Identity.Web
MsalAbstractTokenCacheProvider adapter = new RedisTokenCacheAdapter();
adapter.Init(cca.AppTokenCache);
In addition MSAL can provide several implementations out of the box:
- a partitioned in memory cache for CCA
- an L1 cache for CCA with eviction options (this already exists in M.I.W based on MemoryCache, but an Msal implementation is possible if using Wilson’s cache with event based evictions)
- MSAL ex cache for public clients (which could move entirely in MSAL by the way)
M.I.W. can also rely on this infrastructure to make it easier to consume their token caches.
Solution 2
interface ITokenCacheSerialization
{
void Write(string cacheKey, byte[] payload, CacheHints hints));
byte[] Read(string cacheKey);
void Delete(string cacheKey);
}
// then MSAL would use it as
IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder
.Create(s_clientIdForConfidentialApp) // <-- can even be seen as a mandatory param for apps
.WithTokenCacheSerialization(ITokenCacheSerialization)
.WithClientSecret(s_confidentialClientSecret)
.Build();
In MSAL 4, we keep the 2 ways of serialization. In MSAL 5, we rely exclusively on the new way - deprecate BeforeAccess
/ AfterAccess
etc. and provide an adapter:
// MSAL 5 migration help
ITokenCacheSerialization seri = new CallbackAdapter() { BeforeAccess = ((notificatation) => { /* old logic */} AfterAccess= ((notificatation) => { /* old logic */} };
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8 (6 by maintainers)
@bgavrilMS : do you think we still need it, now that we have the following: https://docs.microsoft.com/azure/active-directory/develop/msal-net-token-cache-serialization?tabs=aspnet
Sorry, haven’t see this. Let’s continue the discussion on the relevant thread.