我已经使用python27实现了混合服务器端Google登录流程。 webapp向后端发送一个时间代码的地方,后端用refresh_token,id_token和access_token代替。我已经按照此文档实施了此https://developers.google.com/identity/sign-in/web/server-side-flow

但是好像不推荐使用oauth2client。并且根据不建议使用的注释,google-auth没有任何方法来实现一次性代码身份验证流程。

下面的代码处理一次auth_code,并替换为令牌。在没有oauth2client的情况下,针对python 2.7和3.7的最佳方法是什么?

from apiclient import discovery
import httplib2
from oauth2client import client

CLIENT_SECRET_FILE = '/path/to/client_secret.json'

# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
                   CLIENT_SECRET_FILE,
                   ['profile', 'email'],
                   auth_code)

最佳答案

您想在没有oauth2client的情况下实现脚本。


如果我的理解是正确的,那么该修改如何?在此修改中,我使用了google_auth_oauthlib。请认为这只是几个答案之一。

修改后的脚本:

from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build

# Create the flow using the client secrets file from the Google API Console.
flow = Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'],
    redirect_uri='urn:ietf:wg:oauth:2.0:oob')

# Tell the user to go to the authorization URL.
auth_url, _ = flow.authorization_url(prompt='consent')

print('Please go to this URL: {}'.format(auth_url))

# The user will get an authorization code. This code is used to get the access token.
code = input('Enter the authorization code: ')
flow.fetch_token(code=code)
credentials = flow.credentials

# Retrieve file list using Drive API. This is a sample.
service = build('drive', 'v3', credentials=credentials)
files = service.files().list(pageSize=5).execute()
print(files)



在此示例脚本中,运行此脚本时,用于检索授权代码的URL将显示在控制台中。获取代码并将其放入控制台后,启用Drive API后,即可检索文件列表。


参考:


google_auth_oauthlib.flow module


如果我误解了您的问题,而这不是您想要的方向,我深表歉意。

09-27 11:44