Skip to content

Instantly share code, notes, and snippets.

@russau
Last active March 26, 2018 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russau/69af1b660a6ce881387cf82b023d8c10 to your computer and use it in GitHub Desktop.
Save russau/69af1b660a6ce881387cf82b023d8c10 to your computer and use it in GitHub Desktop.
# grab an access_token from the metadata on an instance:
# https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances
# curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google"
# configure gcloud to use a snooping proxy
# gcloud config set core/custom_ca_certs_file /usr/local/lib/python3.6/site-packages/certifi/cacert.pem
#
# https://cloud.google.com/sdk/gcloud/reference/config/set
# export https_proxy=http://localhost:8080
#
# the snooping proxy doesn't capture the grpc commands
# https://github.com/grpc/grpc/blob/master/doc/environment_variables.md
#
from jose import jwt
import time
import json
import requests
epoch = int(time.time())
data = json.load(open('f9558d16ab98.json'))
assertion = {
"iat": epoch + 30,
"exp": epoch + 30,
"iss": "russ-c9-second@mindful-girder-171123.iam.gserviceaccount.com",
"aud": "https://accounts.google.com/o/oauth2/token",
"scope": "https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/devstorage.read_only https://www.googleapis.com/auth/devstorage.read_write"
}
token = jwt.encode(assertion, data['private_key'], algorithm='RS256')
bearer = requests.post('https://accounts.google.com/o/oauth2/token', data=
{'assertion' : token,
'grant_type' : "urn:ietf:params:oauth:grant-type:jwt-bearer"
})
access_token = json.loads(bearer.text)['access_token']
headers = {'authorization':'Bearer ' + access_token}
buckets = requests.get('https://www.googleapis.com/storage/v1/b?project=mindful-girder-171123&projection=noAcl', headers=headers)
print(buckets.text)
# the docs for Cloud Endpoints seems to go over a similar oauth flow
# https://cloud.google.com/endpoints/docs/openapi/service-account-authentication
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment