在Microsoft Graph API中使用MSAL刷新令牌的正确实现是什么?

2024-09-30 06:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个桌面程序,需要用户权限才能访问Sharepoint列表。我已经使用acquire\u token\u silent()方法实现了对用户进行身份验证和检索其令牌所需的结构。由于上传到列表可能需要一些时间,我想确保令牌已刷新。我无法让用户再次登录,因为由于重定向到登录表单,这将停止上载过程。在做了一些研究之后,我实现了下一个代码:

上传数据刷新令牌之前,请检查:

token = _get_token_from_cache(MYSCOPE)
        if not token:
            return redirect(login page)

在数据上传过程中:

token = _get_token_from_cache(MYSCOPE) 
if not token: 
   token = methodB(MYSCOPE)
   if not token: 
      return redirect(login page) 

功能方法B是:


def methodB(scope):
    cache = _load_cache() 
    a = _build_msal_app(cache=cache)
    accounts = cca.get_accounts()
    if accounts:  # So all account(s) belong to the current signed-in user
        result = a.acquire_token_silent(scope, account=accounts[0])
    if not result:
        result = app.acquire_token_by_xxx(scope)
        _save_cache(cache)
        return result

在开始的时候,我已经检查了用户是否登录了,我想知道在上传过程中是否有办法避免登录重定向。提前谢谢


Tags: 用户tokencache列表getreturnif过程
2条回答

如果我们已经有一些最终用户之前已用于登录的帐户,acquire_token_silent将在缓存中找到此帐户的令牌,它将自动为您处理令牌刷新

但如果缓存中没有合适的令牌,则需要向AAD发送请求以获取令牌

您可以使用Username Password Flow避免登录重定向,只有这一个适合您的情况,尽管不建议这样做。有一个使用Python的sample

accounts = app.get_accounts(username=config["username"])
if accounts:
    logging.info("Account(s) exists in cache, probably with token too. Let's try.")
    result = app.acquire_token_silent(config["scope"], account=accounts[0])

if not result:
    logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
    result = app.acquire_token_by_username_password(
        config["username"], config["password"], scopes=config["scope"])

配置文件如下所示:

{
    "authority": "https://login.microsoftonline.com/<your tenant id>",
    "client_id": "your_client_id",
    "username": "your_username@your_tenant.com",
    "password": "This is a sample only. You better NOT persist your password.",
    "scope": ["User.ReadBasic.All"],
    "endpoint": "https://graph.microsoft.com/v1.0/users"
}

我知道这个问题已经有了选择的答案。我想提供一些更相关的信息供您考虑

这篇文章首先提到的应用程序是一个“桌面程序”,但代码片段是从MSAL Python的web应用程序示例中派生出来的。对于桌面程序,最好从MSAL's interactive sample开始,它还负责刷新令牌

这样,您就不需要使用username-password方法,这是不推荐的

相关问题 更多 >

    热门问题