Skip to content

Token Cache Persistence

Hemanth Chittanuru edited this page Aug 6, 2020 · 2 revisions

Token Cache Persistence

In MSAL Go, an in-memory cache is provided when an instance of a public/confidential client application is created. However, to persist the cache between instances of your application, you will need to prove this implementation. The CacheAccessor interface has two methods: BeforeCacheAccess and AfterCacheAccess that take in a CacheContext object. The CacheContext object has two methods that you can use: SerializeCache and DeserializeCache. Here is a naive implementation of CacheAccessor that persists the cache in a JSON file.

type SampleCacheAccessor struct {
	file string
}

func (accessor *SampleCacheAccessor) BeforeCacheAccess(context *msalgo.CacheContext) {
	jsonFile, err := os.Open(accessor.file)
	if err != nil {
		log.Fatal(err)
	}
	defer jsonFile.Close()
	data, err := ioutil.ReadAll(jsonFile)
	if err != nil {
		log.Fatal(err)
	}
	err = context.DeserializeCache(data)
	if err != nil {
		log.Fatal(err)
	}
}

func (accessor *SampleCacheAccessor) AfterCacheAccess(context *msalgo.CacheContext) {
	data, err := context.SerializeCache()
	if err != nil {
		log.Fatal(err)
	}
	err = ioutil.WriteFile(accessor.file, []byte(data), 0644)
	if err != nil {
		log.Fatal(err)
	}
}

You can set the CacheAccessor of the public/confidential client app instance as follows.

clientApp.SetCacheAccessor(sampleCacheAccessor)

Getting Started with MSAL Go

  1. Home
  2. Build and Test
Clone this wiki locally