-
Notifications
You must be signed in to change notification settings - Fork 55
/
main.py
32 lines (25 loc) · 1.33 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Python example for the exchange of auth code to refresh token
# Reference: https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html
from google_auth_oauthlib.flow import Flow
from oauthlib.oauth2.rfc6749.errors import OAuth2Error
CLIENT_SECRETS_FILE = 'YOUR_CLIENT_SECRETS_FILE' # get this from https://console.cloud.google.com/apis/credentials
SCOPES = "openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email" # example scopes
# reference for convenience
def credentials_to_dict(credObject):
return {'token': credObject.token,
'refresh_token': credObject.refresh_token,
'token_uri': credObject.token_uri,
'client_id': credObject.client_id,
'client_secret': credObject.client_secret,
'scopes': credObject.scopes}
if __name__ == "__main__":
auth_code = 'auth_code_from_client'
flow = Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri="postmessage")
try:
flow.fetch_token(code=auth_code)
except OAuth2Error:
# error handling, for example InvalidGrantError for malformed auth_code
print('An error occured')
credentials = flow.credentials
print('access_token:', credentials.token)
print('refresh_token:', credentials.refresh_token)