6
3

More than 3 years have passed since last update.

Google Cloud APIのAccess TokenをPythonで取得する(gcloud auth application-default print-access-tokenのやつ)

Last updated at Posted at 2021-03-30

背景

  • REST APIでGoogle Cloud APIsを実行したいので、Access Token が欲しい
curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
       'config': {...}
     }" "https://speech.googleapis.com/v1p1beta1/speech:longrunningrecognize"
  • 例えば、CloudFunction上で、python経由でshell実行 gcloud auth application-default print-access-token してもaccess tokenは取得できなくて困る(空文字が返る)
  • Pythonだけで上でAccess Tokenを取得したい

実装

getting_access_token_with_python
import google.auth
import google.auth.transport.requests
credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
credentials.refresh(auth_req) #refresh token
print(credentials.token) # prints token

これだと、CloudFunctionからでもAccessTokenが取得できた。

参考

How to get a GCP Bearer token programmatically with python

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3