如何使用 MSAL/Python 针对 Azure AD 控制设备代码身份验证流的超时?

How do I control the timeout of an Device Code Authentication Flow using MSAL/Python against Azure AD?

背景: 我是 运行 python 中的无浏览器应用程序,使用设备代码流通过使用 Python Microsoft 身份验证库 (MSAL) 的令牌缓存通过 Azure Active Directory 进行身份验证。我基于 this blog post. I intend to run this script on a cron job every day, but would like to reduce the time that the msal.acquire_token_by_device_flow() 方法编写的脚本在浏览器中成功验证后等待接收令牌 。看起来默认值大约是 5 小时。这个特定的用例是当 90 天刷新令牌到期并且用户需要重新验证时,我希望脚本不会挂起数小时等待用户重新验证。

我尝试过的: 我试图通过在实例化 PublicClientApplication() 对象时使用继承的 timeout 参数(以秒为单位)来控制它,但它不会影响超时。我没有使用 http_client 参数(在使用 timeout 时提到)。具体来说,我已经尝试了以下两种实例化:

app = msal.PublicClientApplication(client_id = CLIENT_ID, authority=AUTHORITY, token_cache=cache, timeout=60)

app = msal.PublicClientApplication(client_id = CLIENT_ID, authority=AUTHORITY, token_cache=cache, timeout=(60,60))

这些都不会影响我正在寻找的超时。大约 5 小时后,如果我不进行身份验证,msal.acquire_token_by_device_flow() 返回的响应是:

感谢任何帮助,甚至是回复以了解我想做的事情是否可以在脚本中控制。

如果你想随时中止轮询循环,我们可以更改流的“expires_at”键的值。详情请参考here

例如

import requests
import msal
from datetime import datetime
import time
import json
app = msal.PublicClientApplication(client_id='',
                                   authority='')

flow = app.initiate_device_flow(scopes=["User.Read"])

if "user_code" not in flow:
    raise ValueError(
        "Fail to create device flow. Err: %s" % json.dumps(flow, indent=4))
flow['expires_at'] = int(time.time())+20
print(flow["message"])

print(datetime.now())
result = app.acquire_token_by_device_flow(flow)

if "access_token" not in result:
    print(datetime.now())
    print(result)