适用于 Python 的 MSAL 中的自定义令牌缓存序列化Custom token cache serialization in MSAL for Python

在 MSAL Python 中,创建 ClientApplication 的实例时,默认会提供一个内存中令牌缓存,该缓存的留存期与应用会话的持续时间相同。In MSAL Python, an in-memory token cache that persists for the duration of the app session, is provided by default when you create an instance of ClientApplication.

将令牌缓存序列化,使应用的不同会话都可以访问它的功能不是现成提供的。Serialization of the token cache, so that different sessions of your app can access it, is not provided "out of the box." 这是因为,MSAL Python 可以在无法访问文件系统的应用类型(例如 Web 应用)中使用。That's because MSAL Python can be used in app types that don't have access to the file system--such as Web apps. 若要在 MSAL Python 应用中使用持久性的令牌缓存,必须提供自定义令牌缓存序列化。To have a persistent token cache in a MSAL Python app, you must provide custom token cache serialization.

用于序列化令牌缓存的策略各不相同,具体取决于是编写公共客户端应用程序(桌面)还是编写机密客户端应用程序(Web 应用、Web API 或守护程序应用)。The strategies for serializing the token cache differ depending on whether you are writing a public client application (Desktop), or a confidential client application (web app, web API, or daemon app).

公共客户端应用程序的令牌缓存Token cache for a public client application

公共客户端应用程序在用户的设备上运行,管理单个用户的令牌。Public client applications run on a user's device and manage tokens for a single user. 对于这种情况,可将整个缓存序列化成一个文件。In this case, you could serialize the entire cache into a file. 如果你的应用和另一应用可以同时访问缓存,请记得提供文件锁定。Remember to provide file locking if your app, or another app, can access the cache concurrently. SerializableTokenCache 类参考文档中提供的一个简单示例演示了如何在不锁定的情况下将令牌缓存序列化成文件。For a simple example of how to serialize a token cache to a file without locking, see the example in the SerializableTokenCache class reference documentation.

Web 应用(机密客户端应用程序)的令牌缓存Token cache for a Web app (confidential client application)

对于 Web 应用或 Web API,可以使用会话、Redis 缓存或数据库来存储令牌缓存。For web apps or web APIs, you might use the session, or a Redis cache, or a database to store the token cache. 每个用户(每个帐户)应有一个令牌缓存,因此请确保按帐户序列化令牌缓存。There should be one token cache per user (per account) so ensure that you serialize the token cache per account.

后续步骤Next steps

有关如何使用 Windows/Linux Web 应用或 Web API 的令牌缓存的示例,请参阅 ms-identity-python-webappSee ms-identity-python-webapp for an example of how to use the token cache for a Windows or Linux Web app or web API. 该示例适用于调用 Microsoft Graph API 的 Web 应用。The example is for a web app that calls the Microsoft Graph API.