簡體   English   中英

使用Google Compute Engine默認服務帳戶簽名Google Cloud Storage URL

[英]Sign Google Cloud Storage URLs with Google Compute Engine default service account

我正在嘗試使用GCE默認服務帳戶來簽名GCS URL。 我為計算默認服務帳戶賦予了必要的“服務帳戶令牌創建者”角色。 當我嘗試在以下Python代碼中簽名url時,出現錯誤:

import google.auth
import google.auth.iam
from google.auth.transport.requests import Request as gRequest

creds, _ = google.auth.default(request=gRequest(), scopes=[
    'https://www.googleapis.com/auth/cloud-platform',
    'https://www.googleapis.com/auth/devstorage.read_write',
    'https://www.googleapis.com/auth/logging.write',
    'https://www.googleapis.com/auth/firebase',
    'https://www.googleapis.com/auth/compute.readonly',
    'https://www.googleapis.com/auth/userinfo.email',
])
## creds is a google.auth.compute_engine.credentials.Credentials
## creds.service_account_email is '<project-id>-compute@developer.gserviceaccount.com'
signer = google.auth.iam.Signer(
    gRequest(), credentials=creds,
    service_account_email=creds.service_account_email)

signer.sign('stuff')

錯誤:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  <TRUNCATED - my code>
  File "/usr/local/lib/python3.6/dist-packages/google/auth/iam.py", line 101, in sign
    response = self._make_signing_request(message)
  File "/usr/local/lib/python3.6/dist-packages/google/auth/iam.py", line 85, in _make_signing_request
    response.data))
google.auth.exceptions.TransportError: Error calling the IAM signBytes API: b'{\n  "error": {\n    "code": 400,\
n    "message": "Invalid service account email (default).",\n    "status": "INVALID_ARGUMENT"\n  }\n}\n'

是否不允許使用GCE默認SA? 是否有其他不允許的默認SA(特別是Google App Engine Flexible SA)?

您需要兩個角色。 您無法在Google Cloud Console中將其中之一授予默認的GCE服務帳戶。 記下您要使用的服務帳戶電子郵件地址。

[2019年1月19日更新]

創建憑證時,直到需要時才初始化憑證(例如,不請求訪問令牌)。 要預先初始化憑據:

auth_url = "https://www.googleapis.com/oauth2/v4/token"
headers = {}
request = google.auth.transport.requests.Request()
creds.before_request(request, "POST", auth_url, headers)

[END UPDATE]

為您的服務帳戶授予角色roles/iam.serviceAccounts.signBlob

gcloud projects add-iam-policy-binding <project-id> --member=serviceAccount:<project-id>-compute@developer.gserviceaccount.com --role=roles/iam.serviceAccounts.signBlob

現在,該服務帳戶可以使用私鑰對數據簽名。

現在,將此服務帳戶授予角色roles/iam.serviceAccountTokenCreator

gcloud iam service-accounts add-iam-policy-binding <project-id>-compute@developer.gserviceaccount.com --member=<project-id>-compute@developer.gserviceaccount.com --role=roles/iam.serviceAccountTokenCreator

現在,該服務帳戶可以使用該服務帳戶創建令牌。 在命令中,您將為第一個service_account_email授予使用第二個service_account_email的特權。 將此視為委派。 注意,一個角色在項目級別,另一個角色分配給服務帳戶本身。

在我的代碼中,我實際上創建了一個新的服務帳戶,並使用該服務帳戶的電子郵件地址進行簽名。 我向新服務帳戶授予權限(使用第一個命令),並向我的憑據授予使用新服務帳戶的權限(第二個命令)。

暫無
暫無

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

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