使用 JWT 驗證

BigQuery API 接受 JSON Web Token (JWT) 驗證要求。

最佳做法是使用應用程式預設憑證 (ADC) 向 BigQuery 進行驗證。如果無法使用 ADC,且您使用服務帳戶進行驗證,則可改用已簽署的 JWT。JWT 可讓您發出 API 呼叫,而不必向 Google 的授權伺服器傳送網路要求。

您可以透過下列方式使用 JWT 進行驗證:

範圍和目標對象

請盡可能搭配服務帳戶使用範圍。如果無法這麼做,可以使用目標對象宣告。如果是 BigQuery API,請將目標對象值設為 https://bigquery.googleapis.com/。

使用用戶端程式庫建立 JWT

如果服務帳戶金鑰是在 Google Cloud 控制台建立,或使用 gcloud CLI 建立,請使用提供 JWT 簽署功能的用戶端程式庫。以下列出一些適用於熱門程式設計語言的選項:

Java 範例

下列範例使用 Java 適用的 BigQuery 用戶端程式庫建立及簽署 JWT。在用戶端程式庫中,BigQuery API 的預設範圍設為 https://www.googleapis.com/auth/bigquery。

import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.common.collect.ImmutableList;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;

public class Example {
    public static void main(String... args) throws IOException {
        String projectId = "myproject";
        // Load JSON file that contains service account keys and create ServiceAccountCredentials object.
        String credentialsPath = "/path/to/key.json";
        ServiceAccountCredentials credentials = null;
        try (FileInputStream is = new FileInputStream(credentialsPath)) {
          credentials =  ServiceAccountCredentials.fromStream(is);
          // The default scope for BigQuery is used.
          // Alternatively, use `.setScopes()` to set custom scopes.
          credentials = credentials.toBuilder()
              .setUseJwtAccessWithScope(true)
              .build();
        }
        // Instantiate BigQuery client with the credentials object.
        BigQuery bigquery =
                BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
        // Use the client to list BigQuery datasets.
        System.out.println("Datasets:");
        bigquery
            .listDatasets(projectId)
            .iterateAll()
            .forEach(dataset -> System.out.printf("%s%n", dataset.getDatasetId().getDataset()));
    }
}

使用 REST 或 gcloud CLI 建立 JWT

如果是系統管理的服務帳戶,您必須手動組合 JWT,然後使用 REST 方法 projects.serviceAccounts.signJwt 或 Google Cloud CLI 指令 gcloud iam service-accounts sign-jwt 簽署 JWT。如要使用上述任一方法,您必須具備 Service Account Token Creator Identity and Access Management 角色。

gcloud CLI 範例

以下範例顯示的 Bash 指令碼會組合 JWT,然後使用 gcloud iam service-accounts sign-jwt 指令簽署。

#!/bin/bash

SA_EMAIL_ADDRESS="myserviceaccount@myproject."

TMP_DIR=$(mktemp -d /tmp/sa_signed_jwt.XXXXX)
trap "rm -rf ${TMP_DIR}" EXIT
JWT_FILE="${TMP_DIR}/jwt-claim-set.json"
SIGNED_JWT_FILE="${TMP_DIR}/output.jwt"

IAT=$(date '+%s')
EXP=$((IAT+3600))

cat <<EOF > $JWT_FILE
{
  "aud": "https://bigquery.googleapis.com/",
  "iat": $IAT,
  "exp": $EXP,
  "iss": "$SA_EMAIL_ADDRESS",
  "sub": "$SA_EMAIL_ADDRESS"
}
EOF

gcloud iam service-accounts sign-jwt --iam-account $SA_EMAIL_ADDRESS $JWT_FILE $SIGNED_JWT_FILE

echo "Datasets:"
curl -L -H "Authorization: Bearer $(cat $SIGNED_JWT_FILE)" \
-X GET \
"https://bigquery.googleapis.com/bigquery/v2/projects/myproject/datasets?alt=json"

後續步驟