如何使用GCP服务帐号生成令牌以访问Google API

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

How to generate token to access Google apis using GCP service account

问题

我正在尝试生成访问令牌,以访问谷歌API,而无需谷歌的同意屏幕。这将使我们能够实现可以自动执行GCP中某些操作的代码,比如停止虚拟机等等。我倾向于在这个实现中使用dotnet core。

我期望生成一个承载授权令牌,通过它我可以在没有任何环境设置或谷歌OAuth同意屏幕的情况下访问谷歌的REST API。

英文:

I'm trying to generate access token to access google APIs without the google consent screen. It will enable us to implement code which can automate certain actions in GCP like stopping a VM and lots more. I prefer to use dotnet core for this implementation.

I except to generate a bearer auth token through which I can access Google rest APIs without any environment setup or Google OAuth consent screen.

答案1

得分: 1

我已经找到了这个问题的答案,对于正在使用GCP或Google API的社区成员来说会很有用。

首先,您需要为您的GCP帐户下载JSON凭据,请参考此文档下载服务帐号密钥

请参考这个Git仓库gcp-auth,这是一个.NET Core类库,其中包含用于生成JWT、异步交换令牌和获取访问令牌的静态方法。
让我解释一下每个方法以便更清楚理解。

GenerateJwt - 此方法从上一步下载的JSON中的PrivateKey、PrivateKeyID、ServiceAccountEmail以及针对不同API端点的范围(scope),例如对于计算下的Google API,我们有 https://www.googleapis.com/auth/compute

ExchangeTokenAsync - 此方法需要使用前一步生成的JWT以从Google生成实际访问令牌,以便在该范围内访问Google API。

GetAccessTokenAsync - 这是上述两种方法的组合,您需要传递与GenerateJwt中相同的参数。

如果需要进一步解释,请告诉我。

英文:

I have found answer for this question and it will be useful for the community members who are working on GCP or google APIs.
First you have to download json credentials for your gcp account, please refer to this documentation Download service account keys

Please refer to this git repo gcp-auth , it's dotnet core class library which contains static method to GenerateJwt, ExchangeTokenAsync and GetAccessTokenAsync.
Let me explain each method for better clarity.

GenerateJwt - this method generates a signed JWT token from PrivateKey, PrivateKeyID, ServiceAccountEmail which are present in downloaded json from previous step and scope which will be different for different api endpoint like we have https://www.googleapis.com/auth/compute for google apis under compute.

ExchangeTokenAsync - this method need the generated JWT from previous step to generate the actual access token from google which will be valid to access google apis under that scope.

GetAccessTokenAsync - this is combination of above two methods, here you've pass parameters same as passed in GenerateJwt.

Please let me know if it requires any further explanation.

huangapple
  • 本文由 发表于 2023年2月8日 21:29:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386493.html
匿名

发表评论

匿名网友

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

确定