Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authorize a Python Google API client service given an OAuth2 access_token?

I have implemented the python-social-auth library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the access_token received in the response for Google's OAuth2 flow.

My question is: use of the google-api-python-client seems to rely on creating and authorizing a credentials object, then using it to build an API service like so:

...
# send user to Google consent URL, get auth_code in response

credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())

from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)

# use service for API calls...

Since I'm starting with an access_token provided by python-social-auth, how do I create & authorize the API client service for future API calls?

Edit: to clarify, the code above is from the examples provided by Google.

like image 913
Joe Avatar asked Jun 09 '26 09:06

Joe


2 Answers

Given you already have the OAuth2 access token you can use the AccessTokenCredentials class.

The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.

Example:

import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials

credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
like image 162
danielx Avatar answered Jun 11 '26 23:06

danielx


If you have an already refreshed latest access token which is not expired, then you can get service variable as:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials


creds = Credentials("<ACCESS_TOKEN>")
service = build('gmail', 'v1', credentials=creds)

# Call the Gmail API

like image 35
Tanmay Singhal Avatar answered Jun 11 '26 22:06

Tanmay Singhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!