Braden Holt
Braden Holt

Reputation: 1594

Google OAuth2: Getting credentials for authorized user

I'm trying to setup an authorization configuration to use Google API and in the process of determining the best method to get a credentials object for an authorized user.

In this case, I would have an expired access_token and active refresh_token. I should use these to create a Credentials object somehow so that I'm able to query the api using the following Python method:

service = build('calendar', 'v3', http=credentials.authorize(Http()))

The documentation I've found on this points me to Google's deprecated oauth2client library's AccessTokenCredentials class (src: https://developers.google.com/api-client-library/python/guide/aaa_oauth#credentials).

That solution would seem to work however I'm guessing there's a non-deprecated solution that I'm just not seeing at present. Any ideas?

Upvotes: 0

Views: 1288

Answers (1)

Braden Holt
Braden Holt

Reputation: 1594

In case there's another rube out there that was confused by the documentation, which I'm sure will improve. Here's the solution:

from django.conf import settings

from auth_creds.models import AuthCred

from apiclient.discovery import build
import google.oauth2.credentials
import google_auth_oauthlib.flow

def query_api(instance):
    SCOPES = 'https://www.googleapis.com/auth/calendar'
    # acquire credentials from persistent storage
    creds = AuthCred.objects.filter(user=instance.user).last()
    # obtain google credentials object
    credentials = google.oauth2.credentials.Credentials(
        refresh_credentials(creds)
    )
    # build api query
    service = build('calendar', 'v3', credentials=credentials)

def refresh_credentials(creds):
    return {
        'token': creds.access_token,
        'refresh_token': creds.refresh_token,
        'token_uri': creds.access_token_uri,
        'client_id': settings.GOOGLE_CLIENT_ID,
        'client_secret': settings.GOOGLE_CLIENT_SECRET,
    }

Upvotes: 1

Related Questions