0

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 Answers1

2

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.

David
  • 9,288
  • 1
  • 20
  • 52
  • `{"errors":[{"code":"DENIED","message":"Failed to read tags for host...` I am not able to get this authorize working. The account has correct permissions, side by side im able to list the docker tags via _token auth curl. – strzelecki.maciek Sep 29 '17 at 09:25
  • That error message comes from GCR, which has some [special](https://cloud.google.com/container-registry/docs/advanced-authentication) authorization considerations. It's also possible you are authenticated correctly, but not the service account is not authorized for the particular data you are requesting. Can you post the full code making the request? Can you see what GCS permissions your service account has on the aritfact.PROJECT.appspot.com bucket? – David Sep 29 '17 at 15:45