使用 JWT 進行驗證

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

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

您可以透過下列方式使用 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 beta iam service-accounts sign-jwt 簽署 JWT。如要使用這兩種方法,您必須是「服務帳戶符記建立者」身分的 Cloud Identity and Access Management 角色成員。

gcloud CLI 範例

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

#!/bin/bash

SA_EMAIL_ADDRESS="myserviceaccount@myproject.iam.gserviceaccount.com"

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 beta 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"

後續步驟