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 logic. The Java classes and interfaces involved in token cache serialization are the following:
- ITokenCache: Interface representing security token cache.
- ITokenCacheAccessAspect : Interface representing operation of executing code before and after access. You would
@Override
beforeCacheAccess and afterCacheAccess with the logic responsible for serializing and deserializing the cache. - ITokenCacheAccessContext : Interface representing context in which the token cache is accessed.
Below is a naive implementation of custom serialization of the token cache.
Warning
Because the sample code below doesn't showcase the full cache storage lifecycle, we strongly recommend to not copy and paste this into a production environment. Make sure that you're aware of security and access requirements for the token cache.
static class TokenPersistence implements ITokenCacheAccessAspect {
String data;
TokenPersistence(String data) {
this.data = data;
}
@Override
public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
iTokenCacheAccessContext.tokenCache().deserialize(data);
}
@Override
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 =
PublicClientApplication.builder("my_client_id").setTokenCacheAccessAspect(persistenceAspect).build();
Learn more
Learn about Get and remove accounts from the token cache using MSAL for Java.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기