从oauth2 client迁移到google-auth以在Python中检索Google ADC访问令牌

wz8daaqr  于 2023-10-15  发布在  Go
关注(0)|答案(1)|浏览(120)

我有几个Python脚本,设计为由具有GCP权限的最终用户运行,然后由基于组的IAM策略控制。要进行身份验证,用户可以通过在CLI上运行gcloud auth application-default login来生成应用程序默认凭据(ADC)。然后我使用oauth2client的GoogleCredentials()和get_access_token()来获取访问令牌:

from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()
access_token = credentials.get_access_token().access_token

然后,我使用Authorization头部将access_token传递给HTTPS请求,格式如下:

Authorization: Bearer <access_token>

工作正常,但是oauth2client几年前就被弃用了,显然应该使用google-authoauthlib。问题是,我完全找不到检索用户生成的ADC访问令牌的任何示例。似乎应该这样做:

from google.auth import default

credentials = default()
access_token = credentials.token

我基于以下使用服务帐户并正常工作的代码:

from os import environ
from google.oauth2.service_account import Credentials
from google.auth.transport.requests import Request

ADC_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'
SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] 

credentials = Credentials.from_service_account_file(environ.get(ADC_VAR), scopes=SCOPES)
credentials.refresh(Request())
access_token = credentials.token
k3fezbri

k3fezbri1#

这不起作用有几个原因,但我错过的主要事情是google.auth.default()返回一个元组,凭证作为第一个元素。所以一个工作代码示例就像这样:

from google.auth import default
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/cloud-platform']

credentials, project_id = default(scopes=SCOPES, quota_project_id='xxxxxx')
credentials.refresh(Request())
access_token = credentials.token

相关问题