oauth-2.0 - 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 )。
该解决方案似乎可行,但是我猜有一个我目前没有看到的未弃用的解决方案。有任何想法吗?
解决方案
万一还有另一个被文档混淆的问题,我肯定会改进。这是解决方案:
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,
}
推荐阅读
- javascript - 在回调函数中获取变量值
- python - Pandas 性能:loc 与使用排序数据在前 x 行中使用 .head(x)
- android - CSP 框架祖先如何支持 Android Cordova 应用程序
- html - 为什么背景图像滚动?
- javascript - 具有可变填充的 D3 包布局
- javascript - 酶浅渲染总是尝试渲染根 index.js
- powershell - 统一文件集
- r - 如何使用包 lfe 导出具有稳健标准误差或聚集标准误差的结果的回归表?
- python - #tensorflow 如何从主函数中打印变量?
- php - Laravel 创建和授权登录