如何避免MSAL PublicClientApplication重复调用acquire_token_interactive?
解决方案:本地文件缓存令牌,仅首次触发交互式授权
核心思路:通过本地文件保存首次获取的令牌,后续运行时优先读取文件中的令牌,仅当文件不存在或令牌过期时才重新执行交互式授权。
具体实现代码:
import json import time from msal import PublicClientApplication # 替换为你的实际配置 CLIENT_ID = "你的客户端ID" AUTHORITY = "你的权限地址" SCOPE = "你的权限范围" TOKEN_CACHE_PATH = "./token_cache.json" def load_token_from_cache(): """从本地缓存文件加载有效令牌""" try: with open(TOKEN_CACHE_PATH, "r") as f: token_data = json.load(f) # 验证令牌是否未过期(expires_on为时间戳,单位秒) if token_data.get("expires_on", 0) > time.time(): return token_data return None except (FileNotFoundError, json.JSONDecodeError): return None def save_token_to_cache(token_data): """将令牌写入本地缓存文件""" with open(TOKEN_CACHE_PATH, "w") as f: json.dump(token_data, f) # 主逻辑执行 token = load_token_from_cache() if not token: # 首次运行或令牌过期,触发交互式授权 app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY) result = app.acquire_token_interactive(scopes=[SCOPE]) if "access_token" in result: save_token_to_cache(result) token = result else: raise Exception(f"授权失败: {result.get('error_description', '未知错误')}") # 后续业务逻辑使用token中的access_token print(f"当前有效令牌: {token['access_token']}")
- 注意事项:
- 确保脚本拥有当前目录的读写权限,避免缓存文件无法创建/读取
- 令牌过期后会自动重新触发浏览器授权,符合安全规范
- 可根据实际需求调整缓存文件路径(比如放到用户个人目录下,降低误删概率)
内容的提问来源于stack exchange,提问作者cJc
相关产品推荐
相关产品推荐

