0

我尝试在 python 中使用 OAuth2WebServerFlow 获取访问令牌和刷新令牌。但它抛出错误 oauth2client.client.FlowExchangeError: invalid_grantMalformed auth code。

示例代码

from oauth2client.client import OAuth2WebServerFlow
def retrieve_data():
    """
    Run through the OAuth flow and retrieve credentials.
    Returns a dataset (Users.dataSources.datasets):
    https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets
    """
    CLIENT_ID = 'XXXXX'
    CLIENT_SECRET = 'XXXX'
    OAUTH_SCOPE = ['https://www.googleapis.com/auth/userinfo.email']
    REDIRECT_URI = 'XXXXXXX'
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    print('Go to the following link in your browser:')
    print(authorize_url)
    code = input('Enter verification code: ')
    print(code)
    google_data = flow.step2_exchange(code)
    # # http = httplib2.Http()
    # # http = google_data.authorize(http)
    # print(google_data)
    # access_token = google_data.token_response['access_token']
    # print(access_token)

retrieve_data()

我也有授权码。我试图在 step2_exchange 方法中传递代码。它抛出了这个错误('oauth2client.client.FlowExchangeError: invalid_grantMalformed auth code.')如何解决这个问题。

4

1 回答 1

2

请按照以下步骤操作:(1) 转到https://console.cloud.google.com/ (2) 选择您的帐户 (3) 转到“导航菜单”右上角的汉堡菜单 (4) 选择 API 服务并选择“ credential” (5) 创建凭据并将 json 文件下载到您的工作目录 (6) 完成 oauth 客户端屏幕,然后复制并粘贴以下 python 代码

    import pickle
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request

    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    CLIENT_SECRET_FILE = 'e:\\Python Programs\\credentials.json'

    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
      with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
      if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
      else:
        flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
      pickle.dump(creds, token)

    drive_service = build('drive', 'v3', credentials=creds)

这是通过 flow.run_local_server 访问令牌的方式

于 2020-04-25T18:01:38.810 回答