MSAL for Java 中的自定义令牌缓存序列化Custom token cache serialization in MSAL for Java

若要在应用程序实例之间始终使用令牌缓存,需要自定义序列化。To persist the token cache between instances of your application, you will need to customize the serialization. 涉及到令牌缓存序列化的 Java 类和接口如下所示:The Java classes and interfaces involved in token cache serialization are the following:

  • ITokenCache:表示安全令牌缓存的接口。ITokenCache: Interface representing security token cache.
  • ITokenCacheAccessAspect:接口,表示在访问前和访问后对执行代码进行的操作。ITokenCacheAccessAspect: Interface representing operation of executing code before and after access. 可以 @Override beforeCacheAccessafterCacheAccess,让逻辑负责缓存的序列化和反序列化。You would @Override beforeCacheAccess and afterCacheAccess with the logic responsible for serializing and deserializing the cache.
  • ITokenCacheContext:接口,表示访问令牌缓存时所在的上下文。ITokenCacheContext: Interface representing context in which the token cache is accessed.

下面是对令牌缓存序列化/反序列化进行的自定义序列化的简单实现Below is a naive implementation of custom serialization of token cache serialization/deserialization. 请勿将它复制并粘贴到生产环境中。Do not copy and paste this into a production environment.

static class TokenPersistence implements ITokenCacheAccessAspect {
String data;

TokenPersistence(String data) { = data;

public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {

public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
        data = iTokenCacheAccessContext.tokenCache().serialize();
// Loads cache from file
String dataToInitCache = readResource(this.getClass(), "/cache_data/serialized_cache.json");

ITokenCacheAccessAspect persistenceAspect = new TokenPersistence(dataToInitCache);

// By setting *TokenPersistence* on the PublicClientApplication, MSAL will call *beforeCacheAccess()* before accessing the cache and *afterCacheAccess()* after accessing the cache. 
PublicClientApplication app = 

了解详细信息Learn more

了解如何使用 MSAL for Java 在令牌缓存中获取和删除帐户Learn about Get and remove accounts from the token cache using MSAL for Java.