hari prasanth
hari prasanth

Reputation: 746

How to get accesst token using OAuth2WebServerFlow in python?

I tried to get access token and refresh token using OAuth2WebServerFlow in python. but it's throwing error oauth2client.client.FlowExchangeError: invalid_grantMalformed auth code.

Example 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()

I have auth code also. i tried to pass code in step2_exchange method.it's throwing this error ('oauth2client.client.FlowExchangeError: invalid_grantMalformed auth code.') how to solve this issuue.

Upvotes: 0

Views: 2032

Answers (1)

Solomon Raja
Solomon Raja

Reputation: 103

Follow the steps: (1) go to https://console.cloud.google.com/ (2) choose your account (3) Go to "navigation menu" top right burger menu (4) Select API services and choose to "credential" (5) create credentials and download the json file onto your working directory (6) finish oauth client screen also and then copy and paste the following python code

    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)

This is the way to access your token through flow.run_local_server

Upvotes: 3

Related Questions