SerializableTokenCache Class

This serialization can be a starting point to implement your own persistence.

This class does NOT actually persist the cache on disk/db/etc.. Depending on your need, the following simple recipe for file-based, unencrypted persistence may be sufficient:


   import os, atexit, msal
   cache_filename = os.path.join(  # Persist cache into this file
       os.getenv(
           # Automatically wipe out the cache from Linux when user's ssh session ends.
           # See also https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/690
           "XDG_RUNTIME_DIR", ""),
       "my_cache.bin")
   cache = msal.SerializableTokenCache()
   if os.path.exists(cache_filename):
       cache.deserialize(open(cache_filename, "r").read())
   atexit.register(lambda:
       open(cache_filename, "w").write(cache.serialize())
       # Hint: The following optional line persists only when state changed
       if cache.has_state_changed else None
       )
   app = msal.ClientApplication(..., token_cache=cache)
   ...

Alternatively, you may use a more sophisticated cache persistence library, MSAL Extensions, which provides token cache persistence with encryption, and more.

Inheritance
SerializableTokenCache

Constructor

SerializableTokenCache()

Variables

Name Description
has_state_changed

Indicates whether the cache state in the memory has changed since last serialize or deserialize call.

Methods

add
deserialize

Deserialize the cache from a state previously obtained by serialize()

modify
serialize

Serialize the current cache state into a string.

add

add(event, **kwargs)

Parameters

Name Description
event
Required

deserialize

Deserialize the cache from a state previously obtained by serialize()

deserialize(state: str | None) -> None

Parameters

Name Description
state
Required

modify

modify(credential_type, old_entry, new_key_value_pairs=None)

Parameters

Name Description
credential_type
Required
old_entry
Required
new_key_value_pairs
Default value: None

serialize

Serialize the current cache state into a string.

serialize() -> str

Attributes

has_state_changed

has_state_changed = False