Ottenere un token ID

Questa pagina descrive alcuni modi per acquisire un token ID OpenID Connect (OIDC) firmato da Google.

Hai bisogno di 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 servizio o un'applicazione specifici per cui possono essere utilizzati, specificati dal valore della rivendicazione aud. Questo documento utilizza il termine servizio di destinazione per fare riferimento al servizio o all'applicazione per cui è possibile utilizzare il token ID per l'autenticazione.

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

Metodi per ottenere un token ID

Esistono vari modi per ottenere un token ID. Questa pagina descrive i seguenti metodi:

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

Recuperare un token ID dal server di metadati

Quando il codice è in esecuzione su una risorsa a cui può essere collegato un service account, il server di metadati per il servizio associato può in genere fornire un token ID. Il server di metadati genera token ID per il account di servizio collegato. Non puoi ottenere un token ID basato sulle credenziali utente dal server di metadati.

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

Per recuperare un token ID dal server di metadati, esegui una query sull'endpoint di identità per il 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 Auth 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.");
  }
}

Vai

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 di autenticazione Google per Python.


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


def idtoken_from_metadata_server(url: str) -> None:
    """
    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

Utilizzare un servizio di connessione per generare un token ID

Alcuni Google Cloud servizi ti aiutano a chiamare altri servizi. Questi servizi di connessione potrebbero aiutarti 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 rivendicazione 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 scheduler. Puoi configurare Cloud Scheduler in modo che includa un token ID o un token di accesso quando chiama un altro servizio. Per saperne di più, consulta Utilizzo dell'autenticazione con target HTTP.
Cloud Tasks
Cloud Tasks ti consente di gestire l'esecuzione di attività distribuite tasks. Puoi configurare un'attività in modo che includa un token ID o un token di accesso quando chiama un servizio. Per saperne di più, consulta Utilizzo delle attività target HTTP con i token di autenticazione.
Pub/Sub
Pub/Sub consente la comunicazione asincrona tra i servizi. Puoi configurare Pub/Sub in modo che includa un token ID con un messaggio. Per saperne di più, consulta Autenticazione per la sottoscrizione push.
Workflows
Workflows è una piattaforma di orchestrazione completamente gestita che esegue i servizi in un ordine definito da te: un workflow. Puoi definire un workflow in modo che includa un token ID o un token di accesso quando chiama un altro servizio. Per saperne di più, consulta Effettua richieste autenticate da un workflow.

Generare un token ID rappresentando un account di servizio

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

Prima che un'entità possa rappresentare un account di servizio, deve avere un ruolo IAM su quel account di servizio che consenta la rappresentazione. Se l'entità è un altro account di servizio, potrebbe sembrare più semplice fornire direttamente le autorizzazioni richieste a quel account di servizio e consentirgli di rappresentare se stesso. Questa configurazione, nota come auto-rappresentazione, crea una vulnerabilità di sicurezza, perché consente al account di servizio di creare un token di accesso che può essere aggiornato in modo permanente.

La simulazione dell'identità dei service account deve sempre coinvolgere due entità: un'entità che rappresenta il chiamante e il account di servizio la cui identità viene simulata, chiamato account di servizio con privilegi.

Per generare un token ID rappresentando un account di servizio, segui la seguente procedura generale.

Per istruzioni passo passo, consulta Creare un token ID.

  1. Identifica o crea un service account che funga da account di servizio con privilegi.

  2. Identifica i ruoli richiesti per chiamare il servizio di destinazione. Concedi questi ruoli al account di servizio sul servizio di destinazione:

    • Per i servizi Cloud Run, concedi il ruolo Cloud Run Invoker (roles/run.invoker).
    • Per funzioni Cloud Run, concedi il ruolo Cloud Functions Invoker (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 le Credenziali predefinite dell'applicazione (ADC) in modo che utilizzi le credenziali per questa entità.

    Per gli ambienti di sviluppo, l'entità è in genere l'account utente che hai fornito ad ADC utilizzando gcloud CLI. Tuttavia, se esegui l'applicazione su una risorsa a cui è collegato un account di servizio, il service account collegato è l'entità.

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

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

    Sostituisci quanto segue:

    • AUDIENCE: l'URI del servizio di destinazione, ad esempio, http://www.example.com.
    • SERVICE_ACCOUNT_EMAIL: l'indirizzo email del account di servizio con privilegi.
    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d '{"audience": "AUDIENCE", "includeEmail": "true"}' \
    https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateIdToken
    

Generare un token ID generico per lo sviluppo con Cloud Run e Cloud Run 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 Run Function che il chiamante ha le autorizzazioni IAM richieste per chiamare. Questo token non funzionerà per altre applicazioni.

Passaggi successivi