Authenticate and connect to a database

This page describes how to authenticate and connect to your Firestore with MongoDB compatibility database.

Connection requirements

The following are required for Firestore with MongoDB compatibility clients:

  • Drivers must connect in load balanced mode. This prevents the drivers from trying to understand the exact server topology they are connecting to.
  • Drivers must connect with SSL enabled.
  • Drivers must disable retryable writes. Firestore with MongoDB compatibility does not currently support retryable writes.

Retrieve the connection string

The database connection string depends on the UID of the database, the location of database, and the authentication mechanism. The following instructions describe how the connection string is formed.

The exact connection string depends on the authentication mechanism, but the base connection string uses the following format:

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

You can obtain the base connection string in one of the following ways:

Console
  1. In the Google Cloud console, go to the Databases page.

    Go to Databases

  2. In the list of databases, click the database ID of the relevant database.
  3. The Explorer panel displays the base connection string. Copy and use this connection string to connect to your database.
gcloud

Use gcloud firestore database describe to retrieve the UID and location information:

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

Replace DATABASE_ID with the database ID.

The output includes the location and UID of the database. Use this information to construct the base connection string.

Use the base connection string and one of the following methods to authenticate and connect to your database:

Connect with Username and password (SCRAM)

Follow these steps to create a user credential for your database and connect to your database.

Before you begin

To get the permissions that you need to create a user, ask your administrator to grant you the userCredsAdmin (roles/datastore.userCredsAdmin) IAM role on your database. For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Create a user and connect to a database

To create a user for your Firestore with MongoDB compatibility database, use one of the following method:

Google Cloud console
  1. In the Google Cloud console, go to the Databases page.

    Go to Databases

  2. Select a database from the list of databases.
  3. In the navigation menu, click Auth.
  4. Click Add User.
  5. Enter a Username.
  6. Select a role for the new user.
  7. Click Add.

    The new user's password will be displayed in the confirmation dialog.

gcloud CLI
  1. To authenticate with SCRAM, you must first create a user credential. Use the gcloud alpha firestore user-creds command:
    gcloud alpha firestore user-creds create USERNAME --database=DATABASE_ID
    Replace the following:
    • USERNAME: the username to create.
    • DATABASE_ID: the database ID.

    The output of this command includes the user's password.

    The output resembles the following:

    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. By default, this new user credential does not have any permissions. For read and write access to the database, add the roles/datastore.user role for this specific database:

    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"'
    Replace the following:

Use the following connection string to connect to your database with SCRAM:

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

Replace the following:

  • USERNAME: the username.
  • PASSWORD: the password you generated for this user.
  • UID: the UID of the database.
  • LOCATION: the location of the database.
  • DATABASE_ID: the database ID.

Connect with the Google Auth Library

The following code sample registers an OIDC callback handler uses the Google Cloud standard OAuth library.

This library lets you use a number of different types of authentication (Application Default Credentials, Workload Identity Federation).

This requires adding the auth library as a dependency:

// 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'

The following code sample demonstrates how to connect:

val db = MongoClients.create(
    connectIgnite(
      "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 Whether to try and fetch an auth credential from the GCE VM metadata service or whether to call gcloud.
 */
private static MongoClientSettings.Builder connectIgnite(
  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));
}

Replace the following:

  • DATABASE_UID: the name of your project.
  • LOCATION: the location of your database.
  • DATABASE_ID the database ID.

Connect from a Compute Engine VM

You can authenticate and connect to your database using a Compute Engine service account. To do this, create an IAM policy for the Google Cloud project that contains your database.

Before you begin

Configure a user-managed service account for your VM:

Take note of your service account email.

Configure credentials

To grant the service account the roles/datastore.user role for read and write to Firestore, run the following command:

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

Replace the following:

  • PROJECT_NAME: the name of your project.
  • SERVICE_ACCOUNT_EMAIL: the email address for the service account that you created.

Construct the connection string

Use the following format to construct the connection string:

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

Replace the following:

  • DATABASE_UID: the name of your project.
  • LOCATION: the location of your database.
  • DATABASE_ID the database ID.

For more information on retrieving the UID and location, see Retrieve the connection string.

Connect with a temporary access token

You can use a temporary Google Cloud access token to run diagnostic tools such as mongosh. You can use gcloud auth print-access-token to authenticate with a short-term access token. This token is valid for one hour.

For example, use the following command to connect to your database with 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'

Replace the following:

  • DATABASE_UID: the UID of the database
  • LOCATION: the database location
  • DATABASE_ID: a database ID