在不打开浏览器Python的情况下打开授权URL



我在Python中使用google_auth_oauthlib.flow来授权Google Oauth 2帐户。我的代码如下:

from google_auth_oauthlib.flow import InstalledAppFlow
flow = InstalledAppFlow.from_client_secrets_file(
"client_secret_929791903032.apps.googleusercontent.com.json",
scopes=['profile', 'email'])
flow.run_local_server(open_browser=False)
session = flow.authorized_session()
profile_info = session.get(
'https://www.googleapis.com/userinfo/v2/me').json()
print(profile_info)

基于run_local_server()文档,我试图设置open_browser=False,但随后谷歌为我提供了一个URL来授权,看起来是这样的https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=92973191032-hpdm8djidqd8o5nqg2gk366efau34ea6q.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=个人资料+电子邮件&state=oHJmupijpVH2gJEPqTogVVHIEtbVXcr&access_type=离线

点击提供的链接后,我的浏览器会自动打开,并显示名为的用户界面使用谷歌登录,然后我必须在浏览器上手动登录。

所以我的问题是如何在不打开浏览器的情况下打开授权URL?我希望我的代码自动授权,而不需要手动授权。

所以我的问题是如何在不打开的情况下打开授权URL浏览器我希望我的代码在不执行任何操作的情况下自动授权手动。

如果您正在使用G Suite,您可以创建一个服务帐户,并启用Domain Wide Delegation以获得G Suite用户的身份。这只适用于属于G Suite域的用户。

如果您没有使用G Suite,则用户第一次访问您的网站时,您无法绕过用户身份验证屏幕。一旦用户通过offline访问进行身份验证,您就可以保存刷新令牌以供将来使用。

身份验证和授权是在客户端(用户)和谷歌帐户之间进行的。您的软件不涉及凭据部分(用户名、密码等)。用户必须授予谷歌帐户权限,才能允许您的服务访问用户的谷歌身份。

〔编辑1/22/2019-在关于如何保存刷新令牌的问题之后〕

以下代码带有授权并保存刷新令牌:

# pip install google-auth-oauthlib
from google_auth_oauthlib.flow import InstalledAppFlow
# https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'])
cred = flow.run_local_server(
host='localhost',
port=8088,
authorization_prompt_message='Please visit this URL: {url}',
success_message='The auth flow is complete; you may close this window.',
open_browser=True)
with open('refresh.token', 'w+') as f:
f.write(cred._refresh_token)
print('Refresh Token:', cred._refresh_token)
print('Saved Refresh Token to file: refresh.token')

最新更新