gpt4 book ai didi

python - 如何在 python 中使用 MSAL 获取访问 token 时避免在浏览器中弹出标签

转载 作者:行者123 更新时间:2023-12-03 06:07:44 25 4
gpt4 key购买 nike

我正在使用下面的代码片段来获取访问 token 。除了代码本身在浏览器中弹出新标签然后返回访问 token 之外,一切都正常工作。怎样才能避免弹出窗口呢?`

from msal import PublicClientApplication
clientID = <clientID>
scopes= ["https://graph.microsoft.com/.default"]
resource_uri = 'https://graph.microsoft.com/'
tenantID = <tenantID>
authority = "https://login.microsoftonline.com/" + tenantID


publicClientApp = PublicClientApplication(clientID, authority=authority)

accounts = publicClientApp.get_accounts()
result = publicClientApp.acquire_token_silent(scopes=["https://graph.microsoft.com/.default"])
access_token = result["access_token"]
print(access_token)
return access_token`

最佳答案

By default, acquire_token_interactive method involves interaction with a user to authenticate via pop-up window in browser and obtain the token.

为了避免在获取 token 时弹出窗口或用户交互,您需要将身份验证流程更改为用户名密码(委托(delegate))或客户端凭据流程(仅限应用)强>)。

如果您想生成具有委派权限的访问 token ,请通过包含用户名和密码参数运行以下修改后的代码:

from msal import PublicClientApplication
clientID = <clientID>
scopes= ["https://graph.microsoft.com/.default"]
tenantID = <tenantID>
authority = "https://login.microsoftonline.com/" + tenantID
username = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4732342235073f3f3f3f3f3f3f3f6928292a2e243528342821336924282a" rel="noreferrer noopener nofollow">[email protected]</a>"
password = "xxxxxxxxx"

publicClientApp = PublicClientApplication(clientID, authority=authority)
result = publicClientApp.acquire_token_by_username_password(scopes=scopes,username=username,password=password)
access_token = result["access_token"]
print(access_token)

回应:

enter image description here

在授予应用程序权限的仅应用程序场景中,您可以运行以下修改后的代码,使用客户端凭据流生成 token ,无需用户交互或弹出窗口:

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

引用: Authentication flow support in the Microsoft Authentication Library (MSAL) - Microsoft Entra

关于python - 如何在 python 中使用 MSAL 获取访问 token 时避免在浏览器中弹出标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77153291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com