Richiedere un token ID

In questa pagina vengono descritti alcuni modi per acquisire un token ID OpenID Connect (OIDC) firmato da Google.

È necessario un token ID firmato da Google per i seguenti casi d'uso dell'autenticazione:

Per informazioni sui contenuti e sulla durata dei token ID, consulta Token ID.

I token ID hanno un'applicazione o un servizio specifico per cui possono essere utilizzati, specificati dal valore della relativa rivendicazione aud. Questa pagina utilizza il termine servizio di destinazione per fare riferimento al servizio o all'applicazione in cui è possibile utilizzare il token ID per l'autenticazione.

Quando ricevi il token ID, puoi includerlo in un'intestazione Authorization nella richiesta al servizio di destinazione.

Metodi per ottenere un token ID

Esistono diversi modi per ottenere un token ID. In questa pagina vengono descritti i seguenti metodi:

Se hai bisogno di un token ID che venga accettato da un'applicazione non ospitata su Google Cloud, probabilmente puoi utilizzare questi metodi. Tuttavia, devi determinare quali token ID richiede l'applicazione.

Ottenere un token ID dal server dei metadati

Quando il codice è in esecuzione su una risorsa a cui è possibile collegare un account di servizio, il server di metadati per il servizio associato di solito può fornire un token ID. Il server di metadati genera token ID per l'account di servizio collegato. Non puoi ottenere un token ID basato sulle credenziali utente del server dei metadati.

Puoi ottenere un token ID dal server di metadati quando il codice è in esecuzione sui seguenti servizi Google Cloud:

Per recuperare un token ID dal server di metadati, esegui una query sull'endpoint di identità per l'account di servizio, come mostrato in questo esempio.

curl

Sostituisci AUDIENCE con l'URI del servizio di destinazione, ad esempio http://www.example.com.

curl -H "Metadata-Flavor: Google" \
  'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE'

PowerShell

Sostituisci AUDIENCE con l'URI del servizio di destinazione, ad esempio http://www.example.com.

$value = (Invoke-RestMethod `
  -Headers @{'Metadata-Flavor' = 'Google'} `
  -Uri "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE")
$value

Java

Per eseguire questo esempio di codice, devi installare la libreria client di autenticazione per Java.


import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
import com.google.auth.oauth2.IdTokenProvider.Option;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

public class IdTokenFromMetadataServer {

  public static void main(String[] args) throws IOException, GeneralSecurityException {
    // TODO(Developer): Replace the below variables before running the code.

    // The url or target audience to obtain the ID token for.
    String url = "https://example.com";

    getIdTokenFromMetadataServer(url);
  }

  // Use the Google Cloud metadata server to create an identity token and add it to the
  // HTTP request as part of an Authorization header.
  public static void getIdTokenFromMetadataServer(String url) throws IOException {
    // Construct the GoogleCredentials object which obtains the default configuration from your
    // working environment.
    GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();

    IdTokenCredentials idTokenCredentials =
        IdTokenCredentials.newBuilder()
            .setIdTokenProvider((IdTokenProvider) googleCredentials)
            .setTargetAudience(url)
            // Setting the ID token options.
            .setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE))
            .build();

    // Get the ID token.
    // Once you've obtained the ID token, you can use it to make an authenticated call to the
    // target audience.
    String idToken = idTokenCredentials.refreshAccessToken().getTokenValue();
    System.out.println("Generated ID token.");
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	"golang.org/x/oauth2/google"
	"google.golang.org/api/idtoken"
	"google.golang.org/api/option"
)

// getIdTokenFromMetadataServer uses the Google Cloud metadata server environment
// to create an identity token and add it to the HTTP request as part of an Authorization header.
func getIdTokenFromMetadataServer(w io.Writer, url string) error {
	// url := "http://www.example.com"

	ctx := context.Background()

	// Construct the GoogleCredentials object which obtains the default configuration from your
	// working environment.
	credentials, err := google.FindDefaultCredentials(ctx)
	if err != nil {
		return fmt.Errorf("failed to generate default credentials: %w", err)
	}

	ts, err := idtoken.NewTokenSource(ctx, url, option.WithCredentials(credentials))
	if err != nil {
		return fmt.Errorf("failed to create NewTokenSource: %w", err)
	}

	// Get the ID token.
	// Once you've obtained the ID token, you can use it to make an authenticated call
	// to the target audience.
	_, err = ts.Token()
	if err != nil {
		return fmt.Errorf("failed to receive token: %w", err)
	}
	fmt.Fprintf(w, "Generated ID token.\n")

	return nil
}

Node.js

Per eseguire questo esempio di codice, devi installare la libreria di autenticazione Google per Node.js

/**
 * TODO(developer):
 *  1. Uncomment and replace these variables before running the sample.
 */
// const targetAudience = 'http://www.example.com';

const {GoogleAuth} = require('google-auth-library');

async function getIdTokenFromMetadataServer() {
  const googleAuth = new GoogleAuth();

  const client = await googleAuth.getIdTokenClient(targetAudience);

  // Get the ID token.
  // Once you've obtained the ID token, you can use it to make an authenticated call
  // to the target audience.
  await client.idTokenProvider.fetchIdToken(targetAudience);
  console.log('Generated ID token.');
}

getIdTokenFromMetadataServer();

Python

Per eseguire questo esempio di codice, devi installare la libreria Python di autenticazione di Google.


import google
import google.oauth2.credentials
from google.auth import compute_engine
import google.auth.transport.requests


def idtoken_from_metadata_server(url: str):
    """
    Use the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,)
    environment to create an identity token and add it to the HTTP request as part of an
    Authorization header.

    Args:
        url: The url or target audience to obtain the ID token for.
            Examples: http://www.example.com
    """

    request = google.auth.transport.requests.Request()
    # Set the target audience.
    # Setting "use_metadata_identity_endpoint" to "True" will make the request use the default application
    # credentials. Optionally, you can also specify a specific service account to use by mentioning
    # the service_account_email.
    credentials = compute_engine.IDTokenCredentials(
        request=request, target_audience=url, use_metadata_identity_endpoint=True
    )

    # Get the ID token.
    # Once you've obtained the ID token, use it to make an authenticated call
    # to the target audience.
    credentials.refresh(request)
    # print(credentials.token)
    print("Generated ID token.")

Ruby

Per eseguire questo esempio di codice, devi installare la libreria di autenticazione Google per Ruby.

require "googleauth"

##
# Uses the Google Cloud metadata server environment to create an identity token
# and add it to the HTTP request as part of an Authorization header.
#
# @param url [String] The url or target audience to obtain the ID token for
#   (e.g. "http://www.example.com")
#
def auth_cloud_idtoken_metadata_server url:
  # Create the GCECredentials client.
  id_client = Google::Auth::GCECredentials.new target_audience: url

  # Get the ID token.
  # Once you've obtained the ID token, you can use it to make an authenticated call
  # to the target audience.
  id_client.fetch_access_token
  puts "Generated ID token."

  id_client.refresh!
end

Utilizza un servizio di connessione per generare un token ID

Alcuni servizi Google Cloud ti aiutano a chiamare altri servizi. Questi servizi di connessione possono aiutare a determinare quando viene effettuata la chiamata o a gestire un flusso di lavoro che include la chiamata al servizio. I seguenti servizi possono includere automaticamente un token ID, con il valore appropriato per la richiesta aud, quando avviano una chiamata a un servizio che richiede un token ID:

Cloud Scheduler
Cloud Scheduler è un servizio di livello enterprise completamente gestito per la pianificazione di cron job. Puoi configurare Cloud Scheduler in modo da includere un token ID o un token di accesso quando richiama un altro servizio. Per maggiori informazioni, consulta la pagina sull' utilizzo dell'autenticazione con target HTTP.
Cloud Tasks
Cloud Tasks consente di gestire l'esecuzione di attività distribuite. Puoi configurare un'attività in modo da includere un token ID o un token di accesso quando chiama un servizio. Per maggiori informazioni, consulta Utilizzo di attività di destinazione HTTP con i token di autenticazione.
Pub/Sub
Pub/Sub consente la comunicazione asincrona tra i servizi. Puoi configurare Pub/Sub in modo da includere un token ID con un messaggio. Per maggiori informazioni, consulta Autenticazione per sottoscrizione push.
Workflows
Workflows è una piattaforma di orchestrazione completamente gestita che esegue i servizi in un ordine definito da te: un flusso di lavoro. Puoi definire un flusso di lavoro che includa un token ID o un token di accesso quando richiama un altro servizio. Per maggiori informazioni, consulta Effettuare richieste autenticate da un flusso di lavoro.

Genera un token ID impersonando un account di servizio

La simulazione dell'identità degli account di servizio consente a un'entità di generare credenziali di breve durata per un account di servizio attendibile. L'entità può quindi usare queste credenziali per autenticarsi come account di servizio.

Prima che un'entità possa rappresentare un account di servizio, deve avere un ruolo IAM per quell'account di servizio che consenta la rappresentazione. Se l'entità è a sua volta un altro account di servizio, potrebbe sembrare più semplice fornire semplicemente le autorizzazioni richieste direttamente a quell'account di servizio e abilitare l'identità dell'entità stessa. Questa configurazione, nota come furto d'identità, crea una vulnerabilità di sicurezza, perché consente all'account di servizio di creare un token di accesso aggiornabile ininterrottamente.

La simulazione dell'identità degli account di servizio deve sempre includere due entità: un'entità che rappresenta il chiamante e l'account di servizio che viene rappresentato, denominato account di servizio con privilegi.

Per generare un token ID assumendo l'identità di un account di servizio, utilizza la procedura generale riportata di seguito.

Per istruzioni dettagliate, consulta Creare un token ID.

  1. Identifica o crea un account di servizio da utilizzare per l'account di servizio con privilegi.

  2. Identificare i ruoli richiesti per richiamare il servizio di destinazione. Concedi questi ruoli all'account di servizio sul servizio di destinazione:

    • Per i servizi Cloud Run, concedi il ruolo Invoker di Cloud Run (roles/run.invoker).
    • Per Cloud Functions, concedi il ruolo Invoker di Cloud Functions (roles/cloudfunctions.invoker).
    • Per altri servizi di destinazione, consulta la documentazione del prodotto per il servizio.
  3. Identifica l'entità che eseguirà la rappresentazione e configura Credenziali predefinite dell'applicazione (ADC) per utilizzare le credenziali per questa entità.

    Per gli ambienti di sviluppo, l'entità di solito è l'account utente che hai fornito ad ADC mediante gcloud CLI. Tuttavia, se è in esecuzione su una risorsa a cui è collegato un account di servizio, l'account di servizio associato è l'entità.

  4. Concedi all'entità il ruolo Creatore token di identità OpenID Connect dell'account di servizio (roles/iam.serviceAccountOpenIdTokenCreator).

  5. Utilizza l'API IAM Credentials per generare il token ID per l'account di servizio autorizzato.

Genera un token ID generico per lo sviluppo con Cloud Run e Cloud Functions

Puoi utilizzare gcloud CLI per ottenere un token ID per le tue credenziali utente che può essere utilizzato con qualsiasi servizio Cloud Run o Cloud Function che il chiamante dispone delle autorizzazioni IAM necessarie per richiamare. Questo token non funzionerà per altre applicazioni.

Passaggi successivi