如何获取有效令牌以在安装了 SDK 的本地计算机上使用 GCP 数据丢失防护 API?

How to get a valid token to use GCP Data Loss Prevention API on a local machine were SDK is installed?

现在我无法让 Google Cloud Platform Data Loss Prevention (DLP) 客户端库用于 python 在 SSL 代理后面工作(它可以与其他 GCP 客户端库一起正常工作例如用于存储或 bigquery): https://cloud.google.com/dlp/docs/libraries#client-libraries-usage-python

所以我尝试使用request.post在SSL代理后面使用API

url = 'https://dlp.googleapis.com/v2/projects/'+os.environ['PROJECT_ID']+'/content:inspect'

headers = {
    'Content-Type': 'application/json',
    'Authorization':  'Bearer {}'.format(subprocess.run('gcloud auth print-access-token', shell=True, check=True, stdout=subprocess.PIPE).stdout.decode().replace('\n', '').replace('\r', ''))
}

}
json_response = requests.post(url=url, json=parsed, headers=headers, proxies=proxies, verify=True)
json.loads(json_response.text)

这在 CloudShell 上运行良好,但在我安装了 SDK 的本地计算机上运行不正常。原因是 CloudShell:

gcloud auth print-access-token

在我的本地机器上(Windows 或 Mac)给我相同的令牌几分钟,每次执行命令时,我都会得到一个新令牌。在我的本地机器上,如果我用 CloudShell 中的令牌替换 header gcloud 命令,它工作正常。我的本地计算机和 CloudShell.

上都有最新版本的 SDK

问题1:预计每次我们运行 gcloud auth print-access-token本地(SDK),我们都会得到一个新的token ? (在 CloudShell 上几分钟是相同的标记)

问题 2:easiest/best生成令牌的方法是什么?因为 gcloud auth print-access-token 在使用本地机器和 SDK 时似乎不是正确的方法。这不是一个高效的应用程序。这只是为了测试 DLP API.

question 1: it is expected that every time we run gcloud auth print-access-token locally (SDK), we get a new token ? (On CloudShell it is the same token for a period of few minutes)

答案取决于您 运行 代码的位置。当从 Google 计算服务(云 Shell 是虚拟机)运行ning 时,令牌来自元数据服务器。我现在确定令牌是否被缓存或缓存了多长时间。令牌有有效期(默认 3600 秒),因此元数据服务器很容易缓存令牌。如果您的代码 运行ning 在 Google 云之外,则答案取决于所使用的库。

question 2: what is the easiest/best way to generate a token ? since gcloud auth print-access-token doesn't seems the right way to do it when using local machine and SDK. This is not a productive application. This is just to test the DLP API.

从CLI获取token只是为了测试。正常的方法是使用SDK。但是,由于您使用的是 REST API,请阅读我写的这篇关于如何在您自己的代码中创建令牌并在 REST API 中使用它们的文章。我的文章包括 Python 源代码和调用计算 API 以列出项目中的实例的示例。

Google Cloud – Creating OAuth Access Tokens for REST API Calls