如何以编程方式获取GCP承载令牌 [英] How to obtain a GCP Bearer token programatically

查看:110
本文介绍了如何以编程方式获取GCP承载令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcloud auth print-access-token给了我一个以后可以使用的Bearer令牌.令牌看起来像: Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg

gcloud auth print-access-token gives me a Bearer token i can use later on. The token looks like: Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg

我不使用gcloud怎么能获得这样的令牌,最好是通过一些python代码.

How can i obtain such a token without the use of gcloud, preferably through some python code.

#!/usr/bin/python

from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
credentials.get_access_token()
token1 = credentials.access_token
# magic piece of code to convert token1 into the 
# example Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
# type.

推荐答案

您的代码段生成的令牌是标头所需的令牌.您只需将"Authorization"标头设置为"Bearer "+token1.

The token your code snippet generates is the token you need for the header. You should simply be able set the "Authorization" header to "Bearer "+token1.

请注意,访问令牌确实会过期,因此,如果您的应用程序寿命很长,则不能简单地存储访问令牌并永久使用它.最终,您将获得401,并且必须获得新的访问令牌.

Note that access tokens do expire, so if you have a long lived application, you cannot simply store the access token and keep using it forever. Eventually you'll get a 401 and you'll have to get a new access token.

最佳做法是让HTTP调用自动处理401,以获取新的access_token.通常,这也将为您处理缓存访问令牌,因此您不必为此担心.实际上,您可以这样做:

The best practice is to have the HTTP call automatically handle 401s to get a fresh access_token. This usually also will handle caching access tokens for you, so you don't need to worry about this. In fact you can do:

http = credentials.authorize(httplib2.Http())

然后整天使用http来处理您的请求,完全不用担心访问令牌.

And then use http for your requests all day without worrying about the access token at all.

这篇关于如何以编程方式获取GCP承载令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆