Crea credenziali con ambiti

Crea credenziali con gli ambiti delle API Drive e BigQuery.

Esempio di codice

Java

Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di BigQuery per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API BigQuery Java.

Per eseguire l'autenticazione in BigQuery, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;

public class AuthDriveScope {

  public static void main(String[] args) throws IOException {
    setAuthDriveScope();
  }

  public static void setAuthDriveScope() throws IOException {
    // Create credentials with Drive & BigQuery API scopes.
    // Both APIs must be enabled for your project before running this code.
    GoogleCredentials credentials =
        ServiceAccountCredentials.getApplicationDefault()
            .createScoped(
                ImmutableSet.of(
                    "https://www.googleapis.com/auth/bigquery",
                    "https://www.googleapis.com/auth/drive"));

    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery =
          BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();

      // Use the client.
      System.out.println("Auth succeeded with multiple scopes. Datasets:");
      for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
        System.out.printf("Dataset: %s%n", dataset.getDatasetId().getDataset());
      }
    } catch (BigQueryException e) {
      System.out.println("Auth failed due to error: \n" + e.toString());
    }
  }
}

Passaggi successivi

Per cercare e filtrare gli esempi di codice per altri prodotti Google Cloud , consulta il browser degli esempi diGoogle Cloud .