如何避免 msal PublicClientApplication 多次加载 acquire_token_interactive ?

问题描述 投票:0回答:1

我有一个Python脚本,我一遍又一遍地运行,该脚本包括使用:

app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
result = app.acquire_token_interactive(scopes=[SCOPE])

这会在我的互联网浏览器中打开一个窗口。我只希望在第一次运行脚本时发生这种情况。关于如何在下次运行这部分代码时不运行它有什么想法吗?

由于公司内部规则,我不认为使用

acquire_token_silent
是替代方案。

python-3.x azure msal
1个回答
0
投票

如果您希望仅登录一次并在下次尝试中自动获取访问令牌,则必须使用

acquire_token_silent
方法从上次登录的缓存中检索令牌。

或者,您可以切换到其他身份验证流程,例如客户端凭据流程,该流程不涉及任何用户交互并代表应用程序生成令牌。

要使用客户端凭据流程获取访问令牌,您需要授予 Application 类型的 API 权限:

enter image description here

现在,我使用下面的Python代码并成功获得了访问令牌,如下所示:

from msal import ConfidentialClientApplication

clientID = "clientID"
clientSecret = "secret"
scopes= ["https://graph.microsoft.com/.default"] 
tenantID = "tenantID"
authority = "https://login.microsoftonline.com/" + tenantID

app = ConfidentialClientApplication(clientID,clientSecret,authority=authority)
result = app.acquire_token_for_client(scopes=scopes)
access_token = result.get("access_token")
print(access_token)

回复:

enter image description here

当我在 jwt.ms 网站中解码此令牌时,我得到

aud
roles
具有 valid 值的声明:

enter image description here

参考: azure - 如何在 python 中使用 MSAL 获取访问令牌时避免在浏览器中弹出标签 - Thinbug

© www.soinside.com 2019 - 2024. All rights reserved.