Google OAuth2:获取授权用户的凭据

时间:2018-08-06 20:48:38

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

我正在尝试设置一个授权配置以使用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)。

该解决方案似乎可以正常工作,但是我猜想有一个我不曾看到过的未弃用的解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

以防万一还有文档引起困惑的麻烦,我相信这会有所改善。解决方法如下:

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,
    }
相关问题