不打开浏览器Python打开授权网址

Ana*_*SWW 7 python api google-oauth

google_auth_oauthlib.flow在 Python 中使用授权 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 Code Online (Sandbox Code Playgroud)

根据run_local_server()文档,我尝试设置,open_browser=False但 Google 为我提供了一个URL进行授权,它看起来像这样https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=929739191032-hpdm8djidqd8o5nqg2gk366efau34ea6usercontent.apps。 com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=profile+email&state=oHJmupijpVH2gJEPqTogVVHIEtbVXcr&access_type=offline

单击提供的链接后,我的浏览器会自动打开名为Sign in with Google的 UI ,然后我必须在浏览器上手动登录。

所以我的问题是如何在不打开浏览器的情况下打开授权网址?我希望我的代码无需手动操作即可自动授权。

Joh*_*ley 8

所以我的问题是如何在不打开浏览器的情况下打开授权网址?我希望我的代码无需手动操作即可自动授权。

如果您使用的是 G Suite,则可以创建一个服务帐号并启用域范围委派以使用 G Suite 用户的身份。这仅适用于属于您 G Suite 网域的用户。

如果您未使用 G Suite,则无法在用户首次访问您的网站时绕过用户身份验证屏幕。用户通过offline访问身份验证后,您可以保存刷新令牌以供将来使用。

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

[编辑 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')
Run Code Online (Sandbox Code Playgroud)