英文:
How to retrieve access-token from GCP Golang SDK?
问题
我们正在为GCP实施一个应用程序,该应用程序需要oauth2承载令牌来对GCR进行docker身份验证。该应用程序是用Go编写的,并且使用Golang的GCP SDK。
我想知道如何从SDK中获取gcloud auth print-access-token
的结果,但是我找不到如何做到这一点...
英文:
We are implementing an application for GCP which needs the oauth2 bearer token to authenticate docker against GCR. The application is written in Go and it uses the GCP SDK for Golang.
I'd like to get what gcloud auth print-access-token
give from the SDK, but I don't find how to do it...
答案1
得分: 2
你可能可以使用工作负载身份联合(也使用这个库),从而避免使用Google服务帐号密钥,而是使用服务帐号(具有roles/storage.objectAdmin
权限,请参阅GCR:授予IAM角色)和应用程序默认凭据(export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
),请查看DefaultTokenSource
。
从TokenSource
的Token()
返回的Token会给你一个access_token
(以及refresh_token
和过期时间)。
更新
你可以直接使用服务帐号密钥文件(https://cloud.google.com/container-registry/docs/advanced-authentication#json-key)来对Docker客户端进行身份验证,这将简化你的代码(并避免刷新)。文档中再次强调使用服务帐号密钥时要小心。
英文:
Have a look at oauth2/google
.
You may (!?) be able to use workload identity federation (using this library too and thereby avoid using a Google Service Account key) but, using a Service Account (with roles/storage.objectAdmin
see GCR: Granting IAM roles) and Application Default Credentials (export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
) look at DefaultTokenSource
.
The Token returned by Token()
from TokenSource
gives you an access_token
(and refresh_token
and expiry).
Update
You can use the Service Account key file directly to authenticate a Docker client to GCR. This would simplify your code (and avoid refreshing). The document reiterates the caution in using Service Account keys.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论