google-oauth - 可以使用 GKE Workload Identity 访问 Google 表格吗?
问题描述
我目前正在使用GKE Workload Identity从 GKE 中访问 Google Cloud Platform 资源。这对于 Google Cloud Storage 和其他平台资源非常有效。
但是,当我尝试使用 GKE Workload Identity 访问 Google 表格时,我遇到了“身份验证范围不足”的问题。
当我为服务帐户生成一个密钥文件并在我的代码中使用它时,我可以手动将范围设置为https://www.googleapis.com/auth/spreadsheets
. 它按预期工作,我可以访问工作表。如果我将范围更改为https://www.googleapis.com/auth/cloud-platform
,我会收到与 GKE Workload Identity 相同的错误,“身份验证范围不足”。此结果表明服务帐户工作正常,因此问题似乎与分配给 GKE 工作负载标识的范围有关。
使用 GKE Workload Identity,我使用credentials = google.auth.default()
[1] 在 Python 中检索凭据。该credentials
对象具有预期的服务帐户,并且范围设置为https://www.googleapis.com/auth/cloud-platform
。我现在可以访问服务帐户有权访问的存储桶和其他云资源。然而,谷歌表格似乎需要https://www.googleapis.com/auth/spreadsheets
范围,但我还没有找到任何方法来设置它。从 GKE 集群中运行的 GKE 元数据服务器检索工作负载身份(服务帐户)和范围。据我所知,GKE 工作负载标识的范围似乎被“硬编码”为https://www.googleapis.com/auth/cloud-platform
. 我没有找到有关这是否可以更改的信息。
(我尝试将电子表格范围添加到 GKE 节点 oauth 范围。没有效果。根据我从文档中可以理解的内容,它应该是不相关的。)
(当然,我可以只使用密钥文件来完成这项工作,但 GKE 工作负载身份的全部意义在于避免安全地生成和分发密钥的所有麻烦)
解决方案
从google-auth
指南中,您是否像这样设置电子表格范围?
credentials, project = google.auth.default(
scopes=['https://www.googleapis.com/auth/spreadsheets'])
我在使用默认客户端时看到了一些相同的行为,但是在使用 curl 进行测试时,我确实使用 Workload Identity 取得了一些成功。
我们可以curl
在测试 pod 上执行流程(例如部署一个 ubuntu pod 并安装 curl)。您应该能够通过 curl gke-metadata-server 在 GKE pod 上验证作用域令牌是否按预期运行:
$ curl -H "Metadata-Flavor: Google" http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token?scopes=https%3A//www.googleapis.com/auth/spreadsheets%20
然后我们可以像这样使用在对工作表 API 的请求中返回的令牌,假设我们已经设置了ACCESS_TOKEN
和SPREADSHEET_ID
环境变量:
$ curl -X GET -H "Authorization: Bearer $ACCESS_TOKEN" https://sheets.googleapis.com/v4/spreadsheets/$SPREADSHEET_ID
这将返回有关您的工作表的所有信息,而不是 403 错误。
我相信这是客户端库应该在幕后做的事情,但这里可能存在一些错误。
这是一个运行在配置了 Workload Identity 的 GKE pod 上的 go 应用程序的工作示例(服务帐户已被授予查看工作表 ID 的权限)。
go.mod
module example.com/m
go 1.13
require (
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c
google.golang.org/api v0.48.0
)
main.go
:
package main
import (
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
)
func main() {
client, err := google.DefaultClient(oauth2.NoContext, sheets.SpreadsheetsScope)
if err != nil {
panic(err)
}
srv, err := sheets.New(client)
if err != nil {
panic(err)
}
resp, err := srv.Spreadsheets.Values.Get("REPLACE_WITH_YOUR_SHEET_ID", "REPLACE_WITH_YOUR_RANGE").Do()
if err != nil {
panic(err)
}
fmt.Println(fmt.Sprintf("%+v", resp.Values))
}
FWIW 我注意到使用旧版本的 oauth2 库绝对不适用于 Workload Identity 和范围。更新以使用较新的版本解决了这个问题。
推荐阅读
- angular - 添加 formControlName 属性后组件属性变为空
- teradata - TDWALLETERROR(543):Teradata 钱包错误。助手进程已被跟踪
- intellij-idea - 对 IntelliJ IDEA 代码高亮插件使用 ANTLR 语法?
- excel - 在几个月内修剪字符以仅显示前三个字符
- javascript - 类型“{}”不可分配给类型“IntrinsicAttributes & DropdownProps & Props &
- hibernate - 计数休眠创建实体会话
- php - MAMP 在 Mac 上安装 Redis 扩展
- swift - 收到消息时将徽章添加到聊天按钮
- django - 检查 Django 测试中的表单错误
- javascript - 从包含特定关键字的 json 数据中删除所有对象