多租户单令牌场景下TokenCache实现及AquireTokenAsync缓存疑问
Let’s break down your two questions specifically for your multi-tenant app scenario where you need to store per-tenant access and refresh tokens:
1. Do I have to implement TokenCache.BeforeAccess and TokenCache.AfterAccess?
Short answer: Yes, if you want proper tenant isolation and persistent token storage. Here’s the breakdown:
The default MSAL token cache is a shared in-memory store, which won’t work for multi-tenant apps—you’d end up mixing tokens across tenants, leading to incorrect token retrieval or leaks. These two events are the standard way to build a tenant-isolated cache:
BeforeAccess: Triggers right before MSAL reads from the cache. Use this to load the specific token cache data for the current tenant (e.g., fetch serialized cache bytes from your database using the tenant ID as a key) and populate the MSAL cache with it. Without this, MSAL will use the shared in-memory cache, breaking tenant isolation.AfterAccess: Triggers after MSAL modifies the cache (like after acquiring a new token or refreshing an existing one). Use this to save the updated cache data back to your storage, linked to the current tenant ID. Skip this, and any new tokens or refresh token updates won’t persist across app restarts or requests.
While custom cache providers might handle isolation automatically, these two events are the recommended approach for MSAL-based multi-tenant token management.
2. Will calling AcquireTokenAsync overwrite existing cached content?
It depends on the context:
- Same tenant, user, and scope: Yes, MSAL will automatically update the cache. When you fetch a new access token (via authorization code flow or refresh token flow), MSAL replaces the old access token with the new one. If your identity provider returns a fresh refresh token (common in many systems), it will also replace the existing refresh token in the cache.
- Different tenant, user, or scope: No—if you’ve implemented tenant isolation via the
BeforeAccess/AfterAccessevents, tokens from one tenant won’t interfere with another. Each tenant’s cache is loaded and saved independently, so new tokens for Tenant A won’t overwrite anything in Tenant B’s cache.
A key note: When using AcquireTokenByAuthorizationCodeAsync for a new tenant, it adds the new token set to the tenant’s specific cache (after you load it in BeforeAccess), rather than overwriting unrelated entries.
内容的提问来源于stack exchange,提问作者Janilson

