首页 > 解决方案 > Google OAuth2:获取授权用户的凭据

问题描述

我正在尝试设置授权配置以使用 Google API,并在确定为授权用户获取凭据对象的最佳方法的过程中。

在这种情况下,我将拥有一个已过期access_token且处于活动状态的refresh_token. 我应该使用它们以某种方式创建一个 Credentials 对象,以便能够使用以下 Python 方法查询 api:

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

我在此找到的文档将我指向 Google 已弃用的 oauth2client 库的AccessTokenCredentials类(src:https ://developers.google.com/api-client-library/python/guide/aaa_oauth#credentials )。

该解决方案似乎可行,但是我猜有一个我目前没有看到的未弃用的解决方案。有任何想法吗?

标签: oauth-2.0google-apigoogle-calendar-api

解决方案


万一还有另一个被文档混淆的问题,我肯定会改进。这是解决方案:

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,
    }

推荐阅读