关于api:无需打开浏览器Python即可打开授权URL

Open the authorization URL without opening browser Python

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,但是Google向我提供了一个要授权的URL,看起来像这样https://accounts.google.com/o/oauth2/auth?response_type=code


So my question is how to open the authorization URL without opening
browser? I want my code automatically authorize without doing
manually.

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

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

身份验证和授权位于客户端(用户)和Google帐户之间。您的软件不参与凭据部分(用户名,密码等)。用户必须授予Google帐户权限,以允许您的服务访问用户的Google身份。

[编辑1/22/2019-询问如何保存刷新令牌的问题]

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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')