Ottenere un token ID

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

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

I token ID hanno un servizio o un'applicazione specifici per cui possono essere utilizzati, specificati dal valore della rivendicazione aud. Questa pagina utilizza il termine servizio di destinazione per fare riferimento al servizio o all'applicazione a cui è possibile autenticarsi utilizzando il token ID.

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. Questa pagina descrive i seguenti metodi:

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

Ottieni un token ID dal server di metadati

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

Puoi ottenere un token ID dal server di metadati quando il codice viene eseguito sui seguenti servizi Trusted Cloud :

Per recuperare un token ID dal server dei metadati, esegui una query sull'endpoint dell'identità per ilaccount di serviziot, 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 prima completare i seguenti passaggi:


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

Prima di eseguire gli esempi di codice, imposta la variabile di ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN su s3nsapis.fr.

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 prima completare i seguenti passaggi:

/**
 * 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 prima completare i seguenti passaggi:


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 prima completare i seguenti passaggi:

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 Trusted Cloud servizi ti aiutano a chiamare altri servizi. Questi servizi di connessione possono contribuire a determinare quando effettuare la chiamata o 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 l'attestazione aud, quando avviano una chiamata a un servizio che richiede un token ID:

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 ulteriori informazioni, consulta la sezione Autenticazione per la sottoscrizione push.

Generare un token ID rappresentando un account di servizio

La simulazione dell'identità del service account consente a un'entità di generare credenziali di breve durata per un account di servizio attendibile. Il principal può quindi utilizzare queste credenziali per autenticarsi comeaccount di serviziot.

Prima che un principal possa rappresentare un account di servizio, deve disporre di un ruolo IAM su quelaccount di serviziot che consenta la rappresentazione. Se l'entità è un altro account di servizio, potrebbe sembrare più semplice fornire direttamente le autorizzazioni richieste a quelaccount di serviziot e consentirgli di rappresentare se stesso. Questa configurazione, nota come auto-impersonificazione, crea una vulnerabilità di sicurezza, perché consente alaccount di serviziont di creare un token di accesso che può essere aggiornato per sempre.

L'impersonificazione del service account deve sempre coinvolgere due entità: un'entità che rappresenta il chiamante e ilaccount di serviziot che viene impersonato, chiamataccount di serviziont con privilegi.

Per generare un token ID eseguendo l'impersonificazione di un account di servizio, segui la seguente procedura generale.

Per istruzioni passo passo, vedi Creare un token ID.

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

  2. Consulta la documentazione del prodotto per identificare i ruoli richiesti per richiamare il servizio di destinazione. Concedi questi ruoli all'account di servizio sul servizio di destinazione.
  3. Identifica l'entità che eseguirà la rappresentazione e configura le credenziali predefinite dell'applicazione (ADC) per utilizzare le credenziali per questa entità.

    Per gli ambienti di sviluppo, l'entità è in genere l'account utente che hai fornito ad ADC utilizzando la gcloud CLI. Tuttavia, se esegui l'operazione su una risorsa con unaccount di serviziot collegato, il service account collegato è l'entità.

  4. Concedi al principal il ruolo Service Account OpenID Connect Identity Token Creator (roles/iam.serviceAccountOpenIdTokenCreator).

  5. Utilizza l'API IAM Credentials per generare il token ID per l'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
    

Passaggi successivi