Tuesday, 24 December 2019

extending the life of a access_token for google Oauth2

I am using the below code to obtain a access_token for google Oauth2 services. The logic is simple.

  1. Execute the code
  2. if there's a token (saved at the file token.txt), use it
  3. If there's not a token, use the browser-based flow.run_console(); save access token to file
  4. return build() of session

My question is, is there a way to extend the token's life past 3600 seconds? like a month? or better? Thanks

Code:

def get_service(ServiceName, API_VERSION):
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    creds = json.loads(Path(CLIENT_SECRETS_FILE).read_text())

    if Path(token).exists():
      access_token = Path(token).read_text()
      credentials = Credentials(
        None,
        refresh_token=access_token,
        token_uri="https://accounts.google.com/o/oauth2/token",
        client_id=creds['installed']['client_id'],
        client_secret=creds['installed']['client_secret']
      )
    else:
      credentials = flow.run_console()
      with open(token, 'w') as filetowrite:
            filetowrite.write(credentials.token)

    return build(ServiceName, API_VERSION, credentials = credentials)


from extending the life of a access_token for google Oauth2

No comments:

Post a Comment