簡體   English   中英

如何僅使用訪問令牌對 gcloud 進行身份驗證?

[英]How to authenticate with gcloud using just access token?

所以我想知道是否有辦法通過訪問令牌對 gcloud 實用程序命令進行身份驗證? 例如,如果我通過 gcloud auth print-access-token 獲得訪問令牌,然后在另一台計算機上執行 gcloud auth ${access_token}

那可能嗎?

我認為默認情況下 Gcloud 身份驗證令牌會在 60 分鍾內到期。

要為其他人或設備提供長期運行的訪問權限,您將使用 IAM 提供對其帳戶的訪問權限,以執行您需要他們執行的功能(通過他們執行自己的 gcloud 身份驗證)。

如果這不是一個選項,您可以創建一個服務帳戶,導出該服務帳戶的密鑰,並向他們提供密鑰,他們可以通過在執行 gcloud 命令之前設置GOOGLE_APPLICATION_CREDENTIALS變量從控制台/終端進行身份驗證。

例如

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

資源

可以通過此處概述的三種方式直接使用訪問令牌,我總結如下:

  1. 聲明CLOUDSDK_AUTH_ACCESS_TOKEN環境變量,參見https://cloud.google.com/sdk/docs/authorizing

  2. --access_token_file標志,參見https://cloud.google.com/sdk/gcloud/reference#--access-token-file

  3. access_token_file的配置,見https://cloud.google.com/sdk/gcloud/reference/config/set並搜索 access_token_file

實踐經驗

我使用 Google Cloud SDK 413.0.0 和 Python 客戶端google-storage-client嘗試了一些東西,並學到了一些相關的東西。

1.選項適用於gcloud ,但不是所有客戶端

下面的所有選項都可以使用憑據設置gcloud CLI。

  • export CLOUDSDK_AUTH_ACCESS_TOKEN=<access token>
  • gcloud config set auth/access_token_file $(pwd)/my-access-token.txt
  • gcloud storage ls <bucket> --access_token_file=$(pwd)/my-access-token.txt

2. Python 客戶不尊重上面列出的選項

這個 github 問題中,要求 Google 的 Python 庫支持CLOUDSDK_AUTH_ACCESS_TOKEN

但是,他們可以像這樣直接使用訪問令牌:

# Example on using a temporary GCP access token.
# 
# To acquire a token from some location, run
# 
#     gcloud auth print-access-token
#
# To use it with python libraries like google-cloud-storage, first create a
# credentials object to pass to the client.
#
import getpass
from google.cloud import storage
from google.oauth2.credentials import Credentials

# import an access token
# - option 1: read an access token from a file
with open("my-access-token.txt") as f:
    access_token = f.read().strip()
# - option 2: read an access token from user input
access_token = getpass.getpass("Enter access token: ")

# setup a storage client using credentials
credentials = Credentials(access_token)
storage_client = storage.Client(credentials=credentials)

# test the storage client by trying to list content in a google storage bucket
bucket_name = "something"  # don't include gs:// here
blobs = list(storage_client.list_blobs(bucket_name))
print(len(blobs))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM