gpt4 book ai didi

python - 自动关闭 localhost 选项卡 msal 库

转载 作者:行者123 更新时间:2023-12-03 01:15:56 25 4
gpt4 key购买 nike

我正在为 python 使用 msal 库,并且我已完成在 Microsoft Azure 上的所有注册,包括将 http://localhost 设置为事件目录中的重定向 URL能够使用 acquire_token_interactive 函数获取 token


import logging

from pprint import pprint

import msal
import requests

config = {
"authority": "https://login.microsoftonline.com/organizations",
"client_id": "XXXXXXXXXXXXXXX",
"username": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ec6c6c6c6c6dec6c6c6c6b0fdf1f3" rel="noreferrer noopener nofollow">[email protected]</a>",
"client_secret": "XXXXXXXXXXXXXXXXX",
"scope": ["User.ReadBasic.All"],
"endpoint": "https://graph.microsoft.com/v1.0/users"
}


app = msal.PublicClientApplication(
config["client_id"], authority=config["authority"],
# allow_broker=True, # If opted in, you will be guided to meet the prerequisites, when applicable
# See also: https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token-wam#wam-value-proposition
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.readthedocs.io/en/latest/#msal.SerializableTokenCache
)
result = None

accounts = app.get_accounts(username=config.get("username"))
if accounts:
logging.info("Account(s) exists in cache, probably with token too. Let's try.")
print("Account(s) already signed in:")
for a in accounts:
print(a["username"])
chosen = accounts[0] # Assuming the end user chose this one to proceed
print("Proceed with account: %s" % chosen["username"])
# Now let's try to find a token in cache for this account
result = app.acquire_token_silent(config["scope"], account=chosen)

if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
print("A local browser window will be open for you to sign in. CTRL+C to cancel.")
result = app.acquire_token_interactive(

port=5001,

# Only works if your app is registered with redirect_uri as http://localhost
scopes=config["scope"],

# parent_window_handle=..., # If broker is enabled, you will be guided to provide a window handle
login_hint=config.get("username"), # Optional.
# If you know the username ahead of time, this parameter can pre-fill
# the username (or email address) field of the sign-in page for the user,
# Often, apps use this parameter during reauthentication,
# after already extracting the username from an earlier sign-in
# by using the preferred_username claim from returned id_token_claims.
on_before_launching_ui=lambda ui="browser", **kwargs: print(
"A {} will be launched you can close the the tab".format(ui))
# prompt=msal.Prompt.SELECT_ACCOUNT, # Or simply "select_account". Optional. It forces to show account selector page
# prompt=msal.Prompt.CREATE, # Or simply "create". Optional. It brings user to a self-service sign-up flow.
# Prerequisite: https://docs.microsoft.com/en-us/azure/active-directory/external-identities/self-service-sign-up-user-flow
)


if "access_token" in result:
# print(result["access_token"])
pprint(result)
# Calling graph using the access token
graph_response = requests.get( # Use token to call downstream service
config["endpoint"],
headers={'Authorization': 'Bearer ' + result['access_token']}, )
# print("Graph API call result: %s ..." % graph_response.text)
# pprint(graph_response.json())
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You may need this when reporting a bug


认证成功后重定向的内容:认证完成。您现在可以关闭此窗口。链接:localhost:XXX/?code=0.ATAXXXXXX&session_state=8beXXXXXX

如何自动关闭 localhost 选项卡有没有办法自动化这个过程?

最佳答案

经过调查,我发现 success_template参数

我们需要将其添加到 acquire_token_interactive()功能

我已经将JS代码注入(inject)其中,3秒后窗口将关闭

success_template ="""<html><body><script>setTimeout(function(){window.close()}, 3000);</script></body></html> """

关于python - 自动关闭 localhost 选项卡 msal 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74880053/

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