Puoi utilizzare i token JWT per l'autenticazione nei seguenti modi:
Per le chiavi dell'account di servizio create nella Google Cloud console o utilizzando l'interfaccia a riga di comando gcloud, utilizza una libreria client che fornisca la firma JWT.
Se possibile, utilizza gli ambiti con l'account di servizio. In caso contrario, puoi utilizzare una rivendicazione del pubblico.
Per le API BigQuery, imposta il valore del segmento di pubblico su
https://bigquery.googleapis.com/.
Creare JWT con le librerie client
Per le chiavi dell'account di servizio create nella Google Cloud console o utilizzando l'interfaccia a riga di comando gcloud, utilizza una libreria client che fornisca la firma JWT. Il seguente elenco fornisce alcune opzioni appropriate per i linguaggi di programmazione più diffusi:
L'esempio seguente utilizza la libreria client BigQuery per Java per creare e firmare un JWT. L'ambito predefinito per l'API BigQuery è impostato su https://www.googleapis.com/auth/bigquery nella libreria client.
importcom.google.auth.oauth2.ServiceAccountCredentials;importcom.google.cloud.bigquery.BigQuery;importcom.google.cloud.bigquery.BigQueryOptions;importcom.google.common.collect.ImmutableList;importjava.io.FileInputStream;importjava.io.IOException;importjava.net.URI;publicclassExample{publicstaticvoidmain(String...args)throwsIOException{StringprojectId="myproject";// Load JSON file that contains service account keys and create ServiceAccountCredentials object.StringcredentialsPath="/path/to/key.json";ServiceAccountCredentialscredentials=null;try(FileInputStreamis=newFileInputStream(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.BigQuerybigquery=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()));}}
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[[["\u003cp\u003eJSON Web Tokens (JWTs) can be used to authenticate requests to the BigQuery API, offering an alternative to Application Default Credentials (ADC) when using a service account.\u003c/p\u003e\n"],["\u003cp\u003eFor service account keys created via the Google Cloud console or gcloud CLI, client libraries provide JWT signing capabilities.\u003c/p\u003e\n"],["\u003cp\u003eSystem-managed service accounts require manual assembly of the JWT, followed by signing using either the REST API's \u003ccode\u003eprojects.serviceAccounts.signJwt\u003c/code\u003e method or the \u003ccode\u003egcloud beta iam service-accounts sign-jwt\u003c/code\u003e command.\u003c/p\u003e\n"],["\u003cp\u003eWhen using JWTs, the audience value for BigQuery APIs should be set to \u003ccode\u003ehttps://bigquery.googleapis.com/\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eClient libraries, like those in Go, Java, Node.js, PHP, Python, and Ruby, offer specific functionalities for generating and signing JWTs for service accounts.\u003c/p\u003e\n"]]],[],null,["# Authenticate with JWTs\n======================\n\nThe BigQuery API accepts\n[JSON Web Tokens (JWTs)](https://datatracker.ietf.org/doc/rfc7519/) to\nauthenticate requests.\n\nAs a best practice, you should use\n[Application Default Credentials (ADC) to authenticate to BigQuery](/bigquery/docs/authentication).\nIf you can't use ADC and you're using a service account for authentication, then\nyou can\n[use a signed JWT](https://developers.google.com/identity/protocols/oauth2/service-account#jwt-auth)\ninstead. JWTs let you make an API call without a network request to Google's\nauthorization server.\n\nYou can use JWTs to authenticate in the following ways:\n\n- For service account keys created in Google Cloud console or by using the gcloud CLI, [use a client library](#client-libraries) that provides JWT signing.\n- For system-managed service accounts, [use the REST API or the gcloud CLI](#rest-gcloud).\n\n### Scope and Audience\n\nUse [scopes](https://developers.google.com/identity/protocols/oauth2/scopes) with service account when possible. If not possible, you can use an\n[audience claim](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3).\nFor the BigQuery APIs, set the audience value to\n`https://bigquery.googleapis.com/`.\n\n### Create JWTs with client libraries\n\nFor service account keys created in Google Cloud console or by using the\ngcloud CLI, use a client library that provides JWT\nsigning. The following list provides some appropriate options for popular\nprogramming languages:\n\n- Go: [func JWTAccessTokenSourceFromJSON](https://pkg.go.dev/golang.org/x/oauth2/google#JWTAccessTokenSourceFromJSON)\n- Java: [Class ServiceAccountCredentials](/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials)\n- Node.js: [Class JWTAccess](/nodejs/docs/reference/google-auth-library/latest/google-auth-library/jwtaccess)\n- PHP: [ServiceAccountJwtAccessCredentials](/php/docs/reference/cloud-bigquery/latest#authentication)\n- Python: [google.auth.jwt module](https://googleapis.dev/python/google-auth/latest/reference/google.auth.jwt.html)\n- Ruby: [Class: Google::Auth::ServiceAccountJwtHeaderCredentials](https://www.rubydoc.info/gems/googleauth/Google/Auth/ServiceAccountJwtHeaderCredentials)\n\n#### Java example\n\nThe following example uses the\n[BigQuery client library for Java](/bigquery/docs/quickstarts/quickstart-client-libraries)\nto create and sign a JWT. The default scope for BigQuery API is set to `https://www.googleapis.com/auth/bigquery` in the client library. \n\n import com.google.auth.oauth2.https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials.html;\n import com.google.cloud.bigquery.https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.BigQuery.html;\n import com.google.cloud.bigquery.https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.BigQueryOptions.html;\n import com.google.common.collect.ImmutableList;\n\n import java.io.FileInputStream;\n import java.io.IOException;\n import java.net.URI;\n\n public class Example {\n public static void main(String... args) throws IOException {\n String projectId = \"myproject\";\n // Load JSON file that contains service account keys and create ServiceAccountCredentials object.\n String credentialsPath = \"/path/to/key.json\";\n https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials.html credentials = null;\n try (FileInputStream is = new FileInputStream(credentialsPath)) {\n credentials = https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials.html.fromStream(is);\n // The default scope for BigQuery is used. \n // Alternatively, use `.setScopes()` to set custom scopes.\n credentials = credentials.https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials.html#com_google_auth_oauth2_ServiceAccountCredentials_toBuilder__()\n .https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.ServiceAccountCredentials.Builder.html#com_google_auth_oauth2_ServiceAccountCredentials_Builder_setUseJwtAccessWithScope_boolean_(true)\n .build();\n }\n // Instantiate BigQuery client with the credentials object.\n https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.BigQuery.html bigquery =\n https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.BigQueryOptions.html.newBuilder().setCredentials(credentials).build().getService();\n // Use the client to list BigQuery datasets.\n System.out.println(\"Datasets:\");\n bigquery\n .listDatasets(projectId)\n .https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.TableResult.html#com_google_cloud_bigquery_TableResult_iterateAll__()\n .forEach(dataset -\u003e System.out.printf(\"%s%n\", dataset.getDatasetId().getDataset()));\n }\n }\n\n### Create JWTs with REST or the gcloud CLI\n\nFor system-managed service accounts, you must manually assemble the JWT, then\nuse the REST method\n[`projects.serviceAccounts.signJwt`](/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signJwt)\nor the Google Cloud CLI command\n[`gcloud beta iam service-accounts sign-jwt`](https://cloud.google.com/sdk/gcloud/reference/beta/iam/service-accounts/sign-jwt)\nto sign the JWT. To use either of these approaches, you must be a member of the\n[Service Account Token Creator](/iam/docs/understanding-roles#service-accounts-roles)\nIdentity and Access Management role.\n\n#### gcloud CLI example\n\nThe following example shows a bash script that assembles a JWT and then uses the\n`gcloud beta iam service-accounts sign-jwt` command to sign it. \n\n #!/bin/bash\n\n SA_EMAIL_ADDRESS=\"myserviceaccount@myproject.iam.gserviceaccount.com\"\n\n TMP_DIR=$(mktemp -d /tmp/sa_signed_jwt.XXXXX)\n trap \"rm -rf ${TMP_DIR}\" EXIT\n JWT_FILE=\"${TMP_DIR}/jwt-claim-set.json\"\n SIGNED_JWT_FILE=\"${TMP_DIR}/output.jwt\"\n\n IAT=$(date '+%s')\n EXP=$((IAT+3600))\n\n cat \u003c\u003cEOF \u003e $JWT_FILE\n {\n \"aud\": \"https://bigquery.googleapis.com/\",\n \"iat\": $IAT,\n \"exp\": $EXP,\n \"iss\": \"$SA_EMAIL_ADDRESS\",\n \"sub\": \"$SA_EMAIL_ADDRESS\"\n }\n EOF\n\n gcloud beta iam service-accounts sign-jwt --iam-account $SA_EMAIL_ADDRESS $JWT_FILE $SIGNED_JWT_FILE\n\n echo \"Datasets:\"\n curl -L -H \"Authorization: Bearer $(cat $SIGNED_JWT_FILE)\" \\\n -X GET \\\n \"https://bigquery.googleapis.com/bigquery/v2/projects/myproject/datasets?alt=json\"\n\nWhat's next\n-----------\n\n- Learn more about [BigQuery authentication](/bigquery/docs/authentication).\n- Learn how to [authenticate with end-user credentials](/bigquery/docs/authentication/end-user-installed)."]]