驗證及連線至資料庫

本頁面說明如何驗證及連線至與 MongoDB 相容的 Firestore 資料庫。

連線需求

與 MongoDB 相容的 Firestore 用戶端必須符合下列條件:

  • 駕駛人必須以 load balanced 模式連線。 這樣一來,驅動程式就不會嘗試瞭解所連線的確切伺服器拓撲。
  • 驅動程式必須啟用 SSL 才能連線。
  • 驅動程式必須停用可重試的寫入作業。 與 MongoDB 相容的 Firestore 目前不支援可重試的寫入作業。

擷取連線字串

資料庫連線字串取決於資料庫的 UID、資料庫位置和驗證機制。下列操作說明將介紹連線字串的形成方式。

確切的連線字串取決於驗證機制,但基本連線字串採用下列格式:

mongodb://UID.LOCATION.firestore.goog:443/DATABASE_ID?loadBalanced=true&tls=true&retryWrites=false

您可以透過下列其中一種方式取得基本連線字串:

控制台
  1. 前往 Google Cloud 控制台的「Databases」頁面。

    前往「資料庫」

  2. 在資料庫清單中,按一下相關資料庫的資料庫 ID。
  3. 「Explorer」面板會顯示基本連線字串。複製並使用這個連線字串連線至資料庫。
gcloud

使用 gcloud firestore database describe 擷取 UID 和位置資訊:

gcloud firestore databases describe \
--database=DATABASE_ID \
--format='yaml(locationId, uid)'

DATABASE_ID 替換為資料庫 ID。

輸出內容會包含資料庫的位置和 UID。使用這項資訊建構基本連線字串。

使用基本連線字串和下列其中一種方法,驗證並連線至資料庫:

使用使用者名稱和密碼 (SCRAM) 連線

請按照下列步驟建立資料庫的使用者憑證,並連線至資料庫。

事前準備

如要取得建立使用者所需的權限,請要求管理員授予您資料庫的 userCredsAdmin (roles/datastore.userCredsAdmin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

建立使用者並連線至資料庫

如要為與 MongoDB 相容的 Firestore 資料庫建立使用者,請使用下列其中一種方法:

Google Cloud 控制台
  1. 前往 Google Cloud 控制台的「Databases」頁面。

    前往「資料庫」

  2. 從資料庫清單中選取資料庫。
  3. 按一下導覽選單中的「Auth」(驗證)
  4. 點選「Add User」
  5. 輸入使用者名稱
  6. 為新使用者選取角色。
  7. 按一下「新增」

    確認對話方塊會顯示新使用者的密碼。

gcloud CLI
  1. 如要使用 SCRAM 驗證,請先建立使用者憑證。使用 gcloud alpha firestore user-creds 指令:
    gcloud alpha firestore user-creds create USERNAME --database=DATABASE_ID
    請替換下列項目:
    • USERNAME:要建立的使用者名稱。
    • DATABASE_ID:資料庫 ID。

    這項指令的輸出內容會包含使用者密碼。

    輸出結果會與下列內容相似:

    name: projects/PROJECT_NAME/databases/DATABASE_ID/userCreds/USERNAME
    resourceIdentity:
      principal: principal://firestore.googleapis.com/projects/PROJECT_NUMBER/name/databases/DATABASE_ID/userCreds/USERNAME
    securePassword: PASSWORD
  2. 根據預設,這個新使用者憑證沒有任何權限。如要取得資料庫的讀取和寫入權限,請為這個特定資料庫新增 roles/datastore.user 角色:

    gcloud projects add-iam-policy-binding PROJECT_NAME \
    --member='principal://firestore.googleapis.com/projects/PROJECT_NUMBER/name/databases/DATABASE_ID/userCreds/USERNAME' \
    --role=roles/datastore.user \
    --condition='expression=resource.name == "projects/PROJECT_NAME/databases/DATABASE_ID",title="CONDITION_TITLE"'
    請替換下列項目:

使用下列連線字串,透過 SCRAM 連線至資料庫:

mongodb://USERNAME:PASSWORD@UID.LOCATION.firestore.goog:443/DATABASE_ID?loadBalanced=true&authMechanism=SCRAM-SHA-256&tls=true&retryWrites=false

更改下列內容:

  • USERNAME:使用者名稱。
  • PASSWORD:您為這個使用者產生的密碼。
  • UID:資料庫的 UID。
  • LOCATION:資料庫位置。
  • DATABASE_ID:資料庫 ID。

連結 Google 驗證程式庫

下列程式碼範例會註冊 OIDC 回呼處理常式,並使用Google Cloud 標準 OAuth 程式庫

這個程式庫可讓您使用多種驗證類型 (應用程式預設憑證、Workload Identity Federation)。

這需要將驗證程式庫新增為依附元件

// Maven
<dependency>
  <groupId>com.google.auth</groupId>
  <artifactId>google-auth-library-oauth2-http</artifactId>
  <version>1.19.0</version>
</dependency>

// Gradle
implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0'

以下程式碼範例示範如何連線:

val db = MongoClients.create(
    clientSettings(
      "DATABASE_UID",
      "LOCATION"
    ).build()
  ).getDatabase("DATABASE_ID")


/**
 * Creates a connection to a Firestore with MongoDB Compatibility database.
 * @param databaseUid The uid of the database to connect to as a string. For example: f116f93a-519c-208a-9a72-3ef6c9a1f081
 * @param locationId The location of the database to connect to, for example: nam5, us-central1, us-east4 etc...
 * @param environment Determines whether to try and fetch an authentication credential from the
 * Compute Engine VM metadata service or whether to call gcloud.
 */
private static MongoClientSettings.Builder clientSettings(
  String databaseUid: String
  String locationId:String
): MongoClientSettings.Builder {
  MongoCredential credential =
    MongoCredential.createOidcCredential(null)
      .withMechanismProperty(
        MongoCredential.OIDC_CALLBACK_KEY,
        new MongoCredential.OidcCallback() {
          @Override
          MongoCredential.OidcCallbackResult onRequest(
MongoCredential.OidcCallbackContext context) {
     // Customize this credential builder for additional credential types.
     GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
            return new MongoCredential.OidcCallbackResult(
         credentials.getAccessToken().getTokenValue(),
         Duration.between(Instant.now(),
credentials.getAccessToken().getExpirationTime().toInstant()));
          }
        },
      );
  return MongoClientSettings.builder()
    .hosts(listOf(ServerAddress(
        "$databaseUid.$locationId.firestore.goog", 443)))
    .credential(credential)
    .applyToClusterSettings(builder ->
         builder.mode(ClusterConnectionMode.LOAD_BALANCED))
    ).applyToSslSettings(ssl -> ssl.enabled(true));
}

更改下列內容:

  • DATABASE_UID:專案名稱。
  • LOCATION:資料庫位置。
  • DATABASE_ID 資料庫 ID。

從 Compute Engine VM 連線

您可以使用 Compute Engine 服務帳戶驗證及連線至資料庫。如要這麼做,請為包含資料庫的 Google Cloud 專案建立 IAM 政策。

事前準備

為 VM 設定使用者代管的服務帳戶:

記下服務帳戶的電子郵件地址。

設定憑證

如要授予服務帳戶 Firestore 的讀取和寫入 roles/datastore.user 角色,請執行下列指令:

gcloud projects add-iam-policy-binding PROJECT_NAME --member="SERVICE_ACCOUNT_EMAIL" --role=roles/datastore.user

更改下列內容:

  • PROJECT_NAME:專案名稱。
  • SERVICE_ACCOUNT_EMAIL:您建立的服務帳戶電子郵件地址。

建構連線字串

請使用下列格式建構連線字串:

mongodb://DATABASE_UID.LOCATION.firestore.goog:443/DATABASE_ID?loadBalanced=true&tls=true&retryWrites=false&authMechanism=MONGODB-OIDC&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:FIRESTORE

更改下列內容:

  • DATABASE_UID:專案名稱。
  • LOCATION:資料庫位置。
  • DATABASE_ID 資料庫 ID。

如要進一步瞭解如何擷取 UID 和位置,請參閱「擷取連線字串」。

使用臨時存取權杖連線

您可以使用暫時性 Google Cloud 存取權杖執行診斷工具,例如 mongosh。您可以使用gcloud auth print-access-token,透過短期存取權杖進行驗證。這個權杖的有效期限為一小時。

舉例來說,使用以下指令透過 mongosh 連線至資料庫:

mongosh --tls \
      --username access_token --password $(gcloud auth print-access-token) \
      'mongodb://UID.LOCATION.firestore.goog:443/DATABASE_ID?loadBalanced=true&authMechanism=PLAIN&authSource=$external&retryWrites=false'

更改下列內容:

  • DATABASE_UID:資料庫的 UID
  • LOCATION:資料庫位置
  • DATABASE_ID:資料庫 ID