How to obtain a GCP Bearer token programatically

2019-09-16 13:11发布

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

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.

1条回答
放荡不羁爱自由
2楼-- · 2019-09-16 13:26

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.

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.

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())

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

查看更多
登录 后发表回答