Skip to content

Instantly share code, notes, and snippets.

@nownabe
Last active March 4, 2022 07:29
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 nownabe/8f2af49a47f3cc65e29973b60cbb9832 to your computer and use it in GitHub Desktop.
Save nownabe/8f2af49a47f3cc65e29973b60cbb9832 to your computer and use it in GitHub Desktop.
開発者が Cloud Run へ認証する方法

免責

これは非公式ドキュメントです。本番環境へ適用する前に、公式ドキュメントを参照するかご自身での手順のテストをお願いいたします。

This is not an official document. Before using it as production, you should refer to official documentations or test the instructions on yourself.

Written by Shawn Watanabe (Google Cloud Customer Engineer)

Last modified at 2022-03-04.

前提

--allow-unauthenticated ではない (--no-allow-unauthenticatedな) Cloud Runのサービスに対して開発者がリクエストを投げる方法です。

開発時以外の認証については次のドキュメントを参照してください。 認証の概要  |  Cloud Run のドキュメント  |  Google Cloud

以下で説明するコマンドはすべて gcloud auth login 済み、gcloud config set project 済みとします。

環境変数について

以下のコマンド内で利用している環境変数について:

  • RUN_SERVICE - Cloud Run のサービス名 (例: my-service)
  • SERVICE_URL - Cloud Run のサービスのURL (例: https://my-service-xxx.a.run.app)
  • SERVICE_ACCOUNT - サービスアカウントのemail (例: invoker@my-project.iam.gserviceaccount.com)

ユーザーでの認証

権限の付与

Cloud Runにアクセスするユーザーに対して、サービスにアクセスする権限を付与します。

gcloud run services add-iam-policy-binding $RUN_SERVICE \
  --member user:$(gcloud config get-value account) \
  --role roles/run.invoker

IDトークンの取得方法

gcloud auth print-identity-token

cURLコマンドでのリクエスト方法

curl $SERVICE_URL -H "Authorization: Bearer $(gcloud auth print-identity-token)"

Service Account での認証

権限の付与

Cloud Runにアクセスするユーザーに対して、サービスにアクセスする権限を付与します。

gcloud run services add-iam-policy-binding $RUN_SERVICE \
  --member serviceAccount:$SERVICE_ACCOUNT \
  --role roles/run.invoker

IDトークンの取得方法

ユーザーに対して、Service Accountになりすますための権限を付与する。

gcloud iam service-accounts add-iam-policy-binding \
  $SERVICE_ACCOUNT \
  --member user:$(gcloud config get-value account) \
  --role roles/iam.serviceAccountTokenCreator

Service AccountになりすましてIDトークンを取得する

gcloud auth print-identity-token \
  --impersonate-service-account $SERVICE_ACCOUNT \
  --audiences $SERVICE_URL

cURLコマンドでのリクエスト方法

curl $SERVICE_URL \
  -H "Authorization: Bearer $(gcloud auth print-identity-token --impersonate-service-account $SERVICE_ACCOUNT --audiences $SERVICE_URL)"

参考資料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment