如何从GCP Golang SDK中检索访问令牌(access-token)?

huangapple go评论120阅读模式
英文:

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

请看oauth2/google

你可能可以使用工作负载身份联合(也使用这个库),从而避免使用Google服务帐号密钥,而是使用服务帐号(具有roles/storage.objectAdmin权限,请参阅GCR:授予IAM角色)和应用程序默认凭据(export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json),请查看DefaultTokenSource

TokenSourceToken()返回的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.

huangapple
  • 本文由 发表于 2022年1月23日 22:03:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/70822802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定