Limita le autorizzazioni Cloud Storage di una credenziale

Questa pagina spiega come utilizzare i confini di accesso alle credenziali per eseguire il downgrade o limitare le autorizzazioni IAM (Identity and Access Management) che possono essere utilizzate da una credenziale di breve durata.

Puoi utilizzare i confini di accesso alle credenziali per generare token di accesso OAuth 2.0 che rappresentano un account di servizio, ma che hanno meno autorizzazioni rispetto all'account di servizio. Ad esempio, se uno dei tuoi clienti ha bisogno di accedere ai dati di Cloud Storage controllati da te, puoi:

  1. Crea un account di servizio che possa accedere a tutti i bucket Cloud Storage di tua proprietà.
  2. Genera un token di accesso OAuth 2.0 per l'account di servizio.
  3. Applica un confine dell'accesso alle credenziali che consente solo l'accesso al bucket che contiene i dati del cliente.

Come funzionano i confini di accesso alle credenziali

Per eseguire il downgrade delle autorizzazioni, definisci un confine di accesso alle credenziali che specifica le risorse a cui può accedere la credenziale di breve durata, nonché un limite superiore delle autorizzazioni disponibili per ciascuna risorsa. Puoi quindi creare una credenziale di breve durata e scambiarla con una nuova che rispetti il confine dell'accesso alle credenziali.

Se devi concedere alle entità un insieme distinto di autorizzazioni per ogni sessione, l'utilizzo dei limiti di accesso alle credenziali può essere più efficiente rispetto alla creazione di molti account di servizio diversi e alla concessione di un insieme di ruoli diverso a ogni account di servizio.

Esempi di confini di accesso alle credenziali

Le seguenti sezioni mostrano esempi di limiti di accesso alle credenziali per casi d'uso comuni. Utilizzi il confine dell'accesso alle credenziali quando scambia un token di accesso OAuth 2.0 con un token con ambito ridotto.

Limitare le autorizzazioni per un bucket

L'esempio seguente mostra un confine di accesso alle credenziali semplice. Si applica al bucket Cloud Storage example-bucket e imposta il limite superiore alle autorizzazioni incluse nel ruolo Visualizzatore oggetti Storage (roles/storage.objectViewer):

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket"
      }
    ]
  }
}

Limitare le autorizzazioni per più bucket

L'esempio seguente mostra un confine dell'accesso alle credenziali che include regole per più bucket:

  • Bucket Cloud Storage example-bucket-1: per questo bucket sono disponibili solo le autorizzazioni associate al ruolo Visualizzatore oggetti Storage (roles/storage.objectViewer).
  • Bucket Cloud Storage example-bucket-2: per questo bucket sono disponibili solo le autorizzazioni associate al ruolo Autore oggetti Storage (roles/storage.objectCreator).
{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket-1"
      },
      {
        "availablePermissions": [
          "inRole:roles/storage.objectCreator"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket-2"
      }
    ]
  }
}

Limitare le autorizzazioni per oggetti specifici

Puoi anche utilizzare le condizioni IAM per specificare a quali oggetti Cloud Storage può accedere un'entità. Ad esempio, puoi aggiungere una condizione che renda disponibili le autorizzazioni per gli oggetti il cui nome inizia con customer-a:

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket",
        "availabilityCondition": {
          "expression" : "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a')"
        }
      }
    ]
  }
}

Limita le autorizzazioni durante l'elenco degli oggetti

Quando elenchi gli oggetti in un bucket Cloud Storage, chiami un metodo su una risorsa bucket, non su una risorsa oggetto. Di conseguenza, se una condizione viene valutata per una richiesta di elenco e la condizione fa riferimento al nome della risorsa, il nome della risorsa identifica il bucket, non un oggetto all'interno del bucket. Ad esempio, quando elenchi oggetti in example-bucket, il nome della risorsa è projects/_/buckets/example-bucket.

Questa convenzione di denominazione può portare a comportamenti imprevisti quando elenchi gli oggetti. Ad esempio, supponi di volere un confine di accesso alle credenziali che consenta l'accesso in visualizzazione agli oggetti in example-bucket con il prefisso customer-a/invoices/. Potresti provare a utilizzare la seguente condizione nel confine dell'accesso alle credenziali:

Incompleto: condizione che controlla solo il nome della risorsa

resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/')

Questa condizione funziona per la lettura di oggetti, ma non per l'elenco degli oggetti:

  • Quando un'entità tenta di leggere un oggetto in example-bucket con il prefisso customer-a/invoices/, la condizione restituisce true.
  • Quando un'entità tenta di elencare gli oggetti con quel prefisso, la condizione restituisce false. Il valore di resource.name è projects/_/buckets/example-bucket, che non inizia con projects/_/buckets/example-bucket/objects/customer-a/invoices/.

Per evitare questo problema, oltre a utilizzare resource.name.startsWith(), la tua condizione può controllare un attributo API denominato storage.googleapis.com/objectListPrefix. Questo attributo contiene il valore del parametro prefix utilizzato per filtrare l'elenco di oggetti. Di conseguenza, puoi scrivere una condizione che faccia riferimento al valore del parametro prefix.

L'esempio seguente mostra come utilizzare l'attributo API in una condizione. Consente di leggere e elencare gli oggetti in example-bucket con il prefisso customer-a/invoices/:

Completata: condizione che controlla il nome e il prefisso della risorsa

resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/')  ||
    api.getAttribute('storage.googleapis.com/objectListPrefix', '')
                     .startsWith('customer-a/invoices/')

Ora puoi utilizzare questa condizione in un confine dell'accesso alle credenziali:

{
  "accessBoundary": {
    "accessBoundaryRules": [
      {
        "availablePermissions": [
          "inRole:roles/storage.objectViewer"
        ],
        "availableResource": "//storage.googleapis.com/projects/_/buckets/example-bucket",
        "availabilityCondition": {
          "expression":
            "resource.name.startsWith('projects/_/buckets/example-bucket/objects/customer-a/invoices/') || api.getAttribute('storage.googleapis.com/objectListPrefix', '').startsWith('customer-a/invoices/')"
        }
      }
    ]
  }
}

Prima di iniziare

Prima di utilizzare i confini di accesso alle credenziali, assicurati di soddisfare i seguenti requisiti:

  • Devi eseguire il downgrade delle autorizzazioni solo per Cloud Storage, non per altri servizi Google Cloud.

    Se hai bisogno di eseguire il downgrade delle autorizzazioni per altri servizi Google Cloud, puoi creare più account di servizio e concedere un insieme diverso di ruoli a ciascun account di servizio.

  • Puoi utilizzare i token di accesso OAuth 2.0 per l'autenticazione. Altri tipi di credenziali di breve durata non supportano i confini di accesso alle credenziali.

Inoltre, devi abilitare le API richieste:

  • Abilita le API IAM and Security Token Service.

    Abilita le API

Crea una credenziale di breve durata con ambito ridotto

Per creare un token di accesso OAuth 2.0 con autorizzazioni limitate, segui questi passaggi:

  1. Concedi i ruoli IAM appropriati a un account utente o di servizio.
  2. Definisci un confine dell'accesso alle credenziali che imposti un limite superiore per le autorizzazioni disponibili per l'account utente o di servizio.
  3. Crea un token di accesso OAuth 2.0 per l'account utente o di servizio.
  4. Scambia il token di accesso OAuth 2.0 con un nuovo token che rispetti il confine dell'accesso alle credenziali.

Puoi quindi utilizzare il nuovo token di accesso OAuth 2.0 con ambito ridotto per autenticare le richieste in Cloud Storage.

Concedi ruoli IAM

Un confine dell'accesso alle credenziali imposta un limite superiore delle autorizzazioni disponibili per una risorsa. Può sottrarre le autorizzazioni da un'entità, ma non può aggiungere autorizzazioni che non dispone già dell'entità.

Di conseguenza, devi anche concedere all'entità i ruoli che forniscono le autorizzazioni di cui hanno bisogno, in un bucket Cloud Storage o su una risorsa di livello superiore, ad esempio il progetto.

Ad esempio, supponi di dover creare una credenziale di breve durata con ambito ridotto che permetta a un account di servizio di creare oggetti in un bucket:

  • Devi concedere all'account di servizio come minimo un ruolo che includa l'autorizzazione storage.objects.create, ad esempio il ruolo Creatore oggetti Storage (roles/storage.objectCreator). Anche il confine dell'accesso alle credenziali deve includere questa autorizzazione.
  • Puoi anche concedere un ruolo che include più autorizzazioni, ad esempio il ruolo Amministratore oggetti Storage (roles/storage.objectAdmin). L'account di servizio può utilizzare solo le autorizzazioni visualizzate sia nella concessione del ruolo sia nel confine dell'accesso alle credenziali.

Per saperne di più sui ruoli predefiniti per Cloud Storage, consulta Ruoli di Cloud Storage.

Componenti di un confine dell'accesso alle credenziali

Un confine di accesso alle credenziali è un oggetto che contiene un elenco di regole dei confini di accesso. Ogni regola contiene le seguenti informazioni:

  • La risorsa a cui si applica la regola.
  • Il limite superiore delle autorizzazioni disponibili per la risorsa.
  • (Facoltativo) Una condizione che limita ulteriormente le autorizzazioni. Una condizione include quanto segue:
    • Un'espressione della condizione che restituisce true o false. Se restituisce true, l'accesso è consentito, altrimenti l'accesso viene negato.
    • (Facoltativo) Un titolo che identifica la condizione.
    • (Facoltativo) Una descrizione con ulteriori informazioni sulla condizione.

Se applichi un limite di accesso alle credenziali a una credenziale di breve durata, questa potrà accedere solo alle risorse al suo interno. Nessuna autorizzazione disponibile per le altre risorse.

Un confine dell'accesso alle credenziali può contenere fino a 10 regole dei limiti di accesso. Puoi applicare un solo limite di accesso alle credenziali a ogni credenziale di breve durata.

Se rappresentato come oggetto JSON, un confine di accesso alle credenziali contiene i seguenti campi:

Campi
accessBoundary

object

Un wrapper per il confine dell'accesso alle credenziali.

accessBoundary.accessBoundaryRules[]

object

Un elenco di regole per i limiti di accesso da applicare a una credenziale di breve durata.

accessBoundary.accessBoundaryRules[].availablePermissions[]

string

Un elenco che definisce il limite superiore delle autorizzazioni disponibili per la risorsa.

Ogni valore è l'identificatore di un ruolo predefinito o ruolo personalizzato IAM, con il prefisso inRole:. Ad esempio: inRole:roles/storage.objectViewer. Saranno disponibili solo le autorizzazioni in questi ruoli.

accessBoundary.accessBoundaryRules[].availableResource

string

Il nome completo della risorsa del bucket Cloud Storage a cui si applica la regola. Utilizza il formato //storage.googleapis.com/projects/_/buckets/bucket-name.

accessBoundary.accessBoundaryRules[].availabilityCondition

object

Facoltativo. Una condizione che limita la disponibilità delle autorizzazioni a oggetti Cloud Storage specifici.

Utilizza questo campo se vuoi rendere disponibili autorizzazioni per oggetti specifici, anziché per tutti gli oggetti in un bucket Cloud Storage.

accessBoundary.accessBoundaryRules[].availabilityCondition.expression

string

Un'espressione di condizione che specifica gli oggetti Cloud Storage in cui sono disponibili le autorizzazioni.

Per scoprire come fare riferimento a oggetti specifici in un'espressione di condizione, consulta la pagina relativa all'attributo resource.name.

accessBoundary.accessBoundaryRules[].availabilityCondition.title

string

Facoltativo. Una breve stringa che identifica lo scopo della condizione.

accessBoundary.accessBoundaryRules[].availabilityCondition.description

string

Facoltativo. Dettagli sullo scopo della condizione.

Per esempi in formato JSON, consulta Esempi di limiti di accesso alle credenziali in questa pagina.

Creare un token di accesso OAuth 2.0

Prima di creare una credenziale di breve durata con ambito ridotto, devi creare un normale token di accesso OAuth 2.0. Puoi quindi scambiare la credenziale normale con una credenziale con ambito ristretto. Quando crei il token di accesso, utilizza l'ambito OAuth 2.0 https://www.googleapis.com/auth/cloud-platform.

Per creare un token di accesso per un account di servizio, puoi completare il flusso OAuth 2.0 server-server oppure utilizzare l'API Service Account Credentials per generare un token di accesso OAuth 2.0.

Per creare un token di accesso per un utente, consulta Ottenere i token di accesso OAuth 2.0. Puoi anche utilizzare OAuth 2.0 Playground per creare un token di accesso per il tuo Account Google.

Scambiare il token di accesso OAuth 2.0

Dopo aver creato un token di accesso OAuth 2.0, puoi scambiare il token di accesso con un token con ambito ridotto che rispetti il confine dell'accesso alle credenziali. Questo processo in genere coinvolge un broker di token e un consumatore di token:

  • Il token di broker è responsabile della definizione del confine dell'accesso alle credenziali e dello scambio di un token di accesso con un token con ambito ridotto.

    Il token broker può utilizzare una libreria di autenticazione supportata per scambiare automaticamente i token di accesso oppure può chiamare il servizio token di sicurezza per scambiare i token manualmente.

  • Il consumer di token richiede un token di accesso con ambito ridotto al broker di token, quindi utilizza il token di accesso con ambito ridotto per eseguire un'altra azione.

    Il consumer di token può utilizzare una libreria di autenticazione supportata per aggiornare automaticamente i token di accesso prima che scadano. In alternativa, può aggiornare i token manualmente o consentire la scadenza dei token senza aggiornarli.

Scambiare e aggiornare automaticamente il token di accesso

Se crei il broker di token e il consumer di token con una delle lingue seguenti, puoi utilizzare la libreria di autenticazione di Google per scambiare e aggiornare automaticamente i token:

Go

Per Go, puoi scambiare e aggiornare automaticamente i token con la versione v0.0.0-20210819190943-2bc19b11175f o successiva del pacchetto golang.org/x/oauth2.

Per verificare quale versione del pacchetto stai utilizzando, esegui questo comando nella directory dell'applicazione:

go list -m golang.org/x/oauth2

L'esempio seguente mostra come un token broker può generare token con ambito ridotto:


import (
	"context"
	"fmt"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"golang.org/x/oauth2/google/downscope"
)

// createDownscopedToken would be run on the token broker in order to generate
// a downscoped access token that only grants access to objects whose name begins with prefix.
// The token broker would then pass the newly created token to the requesting token consumer for use.
func createDownscopedToken(bucketName string, prefix string) error {
	// bucketName := "foo"
	// prefix := "profile-picture-"

	ctx := context.Background()
	// A condition can optionally be provided to further restrict access permissions.
	condition := downscope.AvailabilityCondition{
		Expression:  "resource.name.startsWith('projects/_/buckets/" + bucketName + "/objects/" + prefix + "')",
		Title:       prefix + " Only",
		Description: "Restricts a token to only be able to access objects that start with `" + prefix + "`",
	}
	// Initializes an accessBoundary with one Rule which restricts the downscoped
	// token to only be able to access the bucket "bucketName" and only grants it the
	// permission "storage.objectViewer".
	accessBoundary := []downscope.AccessBoundaryRule{
		{
			AvailableResource:    "//storage.googleapis.com/projects/_/buckets/" + bucketName,
			AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
			Condition:            &condition, // Optional
		},
	}

	// This Source can be initialized in multiple ways; the following example uses
	// Application Default Credentials.
	var rootSource oauth2.TokenSource

	// You must provide the "https://www.googleapis.com/auth/cloud-platform" scope.
	rootSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return fmt.Errorf("failed to generate rootSource: %w", err)
	}

	// downscope.NewTokenSource constructs the token source with the configuration provided.
	dts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
	if err != nil {
		return fmt.Errorf("failed to generate downscoped token source: %w", err)
	}
	// Token() uses the previously declared TokenSource to generate a downscoped token.
	tok, err := dts.Token()
	if err != nil {
		return fmt.Errorf("failed to generate token: %w", err)
	}
	// Pass this token back to the token consumer.
	_ = tok
	return nil
}

L'esempio seguente mostra come un consumer di token può utilizzare un gestore di aggiornamento per ottenere e aggiornare automaticamente i token con ambito ridotto:


import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	"golang.org/x/oauth2/google"
	"golang.org/x/oauth2/google/downscope"

	"cloud.google.com/go/storage"
	"golang.org/x/oauth2"
	"google.golang.org/api/option"
)

// A token consumer should define their own tokenSource. In the Token() method,
// it should send a query to a token broker requesting a downscoped token.
// The token broker holds the root credential that is used to generate the
// downscoped token.
type localTokenSource struct {
	ctx        context.Context
	bucketName string
	brokerURL  string
}

func (lts localTokenSource) Token() (*oauth2.Token, error) {
	var remoteToken *oauth2.Token
	// Usually you would now retrieve remoteToken, an oauth2.Token, from token broker.
	// This snippet performs the same functionality locally.
	accessBoundary := []downscope.AccessBoundaryRule{
		{
			AvailableResource:    "//storage.googleapis.com/projects/_/buckets/" + lts.bucketName,
			AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
		},
	}
	rootSource, err := google.DefaultTokenSource(lts.ctx, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return nil, fmt.Errorf("failed to generate rootSource: %w", err)
	}
	dts, err := downscope.NewTokenSource(lts.ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
	if err != nil {
		return nil, fmt.Errorf("failed to generate downscoped token source: %w", err)
	}
	// Token() uses the previously declared TokenSource to generate a downscoped token.
	remoteToken, err = dts.Token()
	if err != nil {
		return nil, fmt.Errorf("failed to generate token: %w", err)
	}

	return remoteToken, nil
}

// getObjectContents will read the contents of an object in Google Storage
// named objectName, contained in the bucket "bucketName".
func getObjectContents(output io.Writer, bucketName string, objectName string) error {
	// bucketName := "foo"
	// prefix := "profile-picture-"

	ctx := context.Background()

	thisTokenSource := localTokenSource{
		ctx:        ctx,
		bucketName: bucketName,
		brokerURL:  "yourURL.com/internal/broker",
	}

	// Wrap the TokenSource in an oauth2.ReuseTokenSource to enable automatic refreshing.
	refreshableTS := oauth2.ReuseTokenSource(nil, thisTokenSource)
	// You can now use the token source to access Google Cloud Storage resources as follows.
	storageClient, err := storage.NewClient(ctx, option.WithTokenSource(refreshableTS))
	if err != nil {
		return fmt.Errorf("failed to create the storage client: %w", err)
	}
	defer storageClient.Close()
	bkt := storageClient.Bucket(bucketName)
	obj := bkt.Object(objectName)
	rc, err := obj.NewReader(ctx)
	if err != nil {
		return fmt.Errorf("failed to retrieve the object: %w", err)
	}
	defer rc.Close()
	data, err := ioutil.ReadAll(rc)
	if err != nil {
		return fmt.Errorf("could not read the object's contents: %w", err)
	}
	// Data now contains the contents of the requested object.
	output.Write(data)
	return nil
}

Java

Per Java, puoi scambiare e aggiornare automaticamente i token con la versione 1.1.0 o successive dell'artefatto com.google.auth:google-auth-library-oauth2-http.

Per verificare quale versione di questo artefatto stai utilizzando, esegui il seguente comando Maven nella directory dell'applicazione:

mvn dependency:list -DincludeArtifactIds=google-auth-library-oauth2-http

L'esempio seguente mostra come un token broker può generare token con ambito ridotto:

public static AccessToken getTokenFromBroker(String bucketName, String objectPrefix)
    throws IOException {
  // Retrieve the source credentials from ADC.
  GoogleCredentials sourceCredentials =
      GoogleCredentials.getApplicationDefault()
          .createScoped("https://www.googleapis.com/auth/cloud-platform");

  // Initialize the Credential Access Boundary rules.
  String availableResource = "//storage.googleapis.com/projects/_/buckets/" + bucketName;

  // Downscoped credentials will have readonly access to the resource.
  String availablePermission = "inRole:roles/storage.objectViewer";

  // Only objects starting with the specified prefix string in the object name will be allowed
  // read access.
  String expression =
      "resource.name.startsWith('projects/_/buckets/"
          + bucketName
          + "/objects/"
          + objectPrefix
          + "')";

  // Build the AvailabilityCondition.
  CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition availabilityCondition =
      CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder()
          .setExpression(expression)
          .build();

  // Define the single access boundary rule using the above properties.
  CredentialAccessBoundary.AccessBoundaryRule rule =
      CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
          .setAvailableResource(availableResource)
          .addAvailablePermission(availablePermission)
          .setAvailabilityCondition(availabilityCondition)
          .build();

  // Define the Credential Access Boundary with all the relevant rules.
  CredentialAccessBoundary credentialAccessBoundary =
      CredentialAccessBoundary.newBuilder().addRule(rule).build();

  // Create the downscoped credentials.
  DownscopedCredentials downscopedCredentials =
      DownscopedCredentials.newBuilder()
          .setSourceCredential(sourceCredentials)
          .setCredentialAccessBoundary(credentialAccessBoundary)
          .build();

  // Retrieve the token.
  // This will need to be passed to the Token Consumer.
  AccessToken accessToken = downscopedCredentials.refreshAccessToken();
  return accessToken;
}

L'esempio seguente mostra come un consumer di token può utilizzare un gestore di aggiornamento per ottenere e aggiornare automaticamente i token con ambito ridotto:

public static void tokenConsumer(final String bucketName, final String objectName)
    throws IOException {
  // You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` which will allow the
  // library to seamlessly handle downscoped token refreshes on expiration.
  OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler =
      new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() {
        @Override
        public AccessToken refreshAccessToken() throws IOException {
          // The common pattern of usage is to have a token broker pass the downscoped short-lived
          // access tokens to a token consumer via some secure authenticated channel.
          // For illustration purposes, we are generating the downscoped token locally.
          // We want to test the ability to limit access to objects with a certain prefix string
          // in the resource bucket. objectName.substring(0, 3) is the prefix here. This field is
          // not required if access to all bucket resources are allowed. If access to limited
          // resources in the bucket is needed, this mechanism can be used.
          return getTokenFromBroker(bucketName, objectName.substring(0, 3));
        }
      };

  // Downscoped token retrieved from token broker.
  AccessToken downscopedToken = handler.refreshAccessToken();

  // Create the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler
  // which will handle token expiration.
  // This will allow the consumer to seamlessly obtain new downscoped tokens on demand every time
  // token expires.
  OAuth2CredentialsWithRefresh credentials =
      OAuth2CredentialsWithRefresh.newBuilder()
          .setAccessToken(downscopedToken)
          .setRefreshHandler(handler)
          .build();

  // Use the credentials with the Cloud Storage SDK.
  StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build();
  Storage storage = options.getService();

  // Call Cloud Storage APIs.
  Blob blob = storage.get(bucketName, objectName);
  String content = new String(blob.getContent());
  System.out.println(
      "Retrieved object, "
          + objectName
          + ", from bucket,"
          + bucketName
          + ", with content: "
          + content);
}

Node.js

Per Node.js, puoi scambiare e aggiornare automaticamente i token con la versione 7.9.0 o successive del pacchetto google-auth-library.

Per verificare quale versione del pacchetto stai utilizzando, esegui questo comando nella directory dell'applicazione:

npm list google-auth-library

L'esempio seguente mostra come un token broker può generare token con ambito ridotto:

// Imports the Google Auth libraries.
const {GoogleAuth, DownscopedClient} = require('google-auth-library');
/**
 * Simulates token broker generating downscoped tokens for specified bucket.
 *
 * @param bucketName The name of the Cloud Storage bucket.
 * @param objectPrefix The prefix string of the object name. This is used
 *        to ensure access is restricted to only objects starting with this
 *        prefix string.
 */
async function getTokenFromBroker(bucketName, objectPrefix) {
  const googleAuth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
  });

  // Define the Credential Access Boundary object.
  const cab = {
    // Define the access boundary.
    accessBoundary: {
      // Define the single access boundary rule.
      accessBoundaryRules: [
        {
          availableResource: `//storage.googleapis.com/projects/_/buckets/${bucketName}`,
          // Downscoped credentials will have readonly access to the resource.
          availablePermissions: ['inRole:roles/storage.objectViewer'],
          // Only objects starting with the specified prefix string in the object name
          // will be allowed read access.
          availabilityCondition: {
            expression:
              "resource.name.startsWith('projects/_/buckets/" +
              `${bucketName}/objects/${objectPrefix}')`,
          },
        },
      ],
    },
  };

  // Obtain an authenticated client via ADC.
  const client = await googleAuth.getClient();

  // Use the client to create a DownscopedClient.
  const cabClient = new DownscopedClient(client, cab);

  // Refresh the tokens.
  const refreshedAccessToken = await cabClient.getAccessToken();

  // This will need to be passed to the token consumer.
  return refreshedAccessToken;
}

L'esempio seguente mostra in che modo un consumer di token può fornire un gestore di aggiornamento che ottiene e aggiorna automaticamente i token con ambito ridotto:

// Imports the Google Auth and Google Cloud libraries.
const {OAuth2Client} = require('google-auth-library');
const {Storage} = require('@google-cloud/storage');
/**
 * Simulates token consumer generating calling GCS APIs using generated
 * downscoped tokens for specified bucket.
 *
 * @param bucketName The name of the Cloud Storage bucket.
 * @param objectName The name of the object in the Cloud Storage bucket
 *        to read.
 */
async function tokenConsumer(bucketName, objectName) {
  // Create the OAuth credentials (the consumer).
  const oauth2Client = new OAuth2Client();
  // We are defining a refresh handler instead of a one-time access
  // token/expiry pair.
  // This will allow the consumer to obtain new downscoped tokens on
  // demand every time a token is expired, without any additional code
  // changes.
  oauth2Client.refreshHandler = async () => {
    // The common pattern of usage is to have a token broker pass the
    // downscoped short-lived access tokens to a token consumer via some
    // secure authenticated channel. For illustration purposes, we are
    // generating the downscoped token locally. We want to test the ability
    // to limit access to objects with a certain prefix string in the
    // resource bucket. objectName.substring(0, 3) is the prefix here. This
    // field is not required if access to all bucket resources are allowed.
    // If access to limited resources in the bucket is needed, this mechanism
    // can be used.
    const refreshedAccessToken = await getTokenFromBroker(
      bucketName,
      objectName.substring(0, 3)
    );
    return {
      access_token: refreshedAccessToken.token,
      expiry_date: refreshedAccessToken.expirationTime,
    };
  };

  const storageOptions = {
    projectId: process.env.GOOGLE_CLOUD_PROJECT,
    authClient: oauth2Client,
  };

  const storage = new Storage(storageOptions);
  const downloadFile = await storage
    .bucket(bucketName)
    .file(objectName)
    .download();
  console.log(downloadFile.toString('utf8'));
}

Python

Per Python, puoi scambiare e aggiornare i token automaticamente con la versione 2.0.0 o successive del pacchetto google-auth.

Per verificare quale versione di questo pacchetto stai utilizzando, esegui questo comando nell'ambiente in cui è installato il pacchetto:

pip show google-auth

L'esempio seguente mostra come un token broker può generare token con ambito ridotto:

import google.auth

from google.auth import downscoped
from google.auth.transport import requests

def get_token_from_broker(bucket_name, object_prefix):
    """Simulates token broker generating downscoped tokens for specified bucket.

    Args:
        bucket_name (str): The name of the Cloud Storage bucket.
        object_prefix (str): The prefix string of the object name. This is used
            to ensure access is restricted to only objects starting with this
            prefix string.

    Returns:
        Tuple[str, datetime.datetime]: The downscoped access token and its expiry date.
    """
    # Initialize the Credential Access Boundary rules.
    available_resource = f"//storage.googleapis.com/projects/_/buckets/{bucket_name}"
    # Downscoped credentials will have readonly access to the resource.
    available_permissions = ["inRole:roles/storage.objectViewer"]
    # Only objects starting with the specified prefix string in the object name
    # will be allowed read access.
    availability_expression = (
        "resource.name.startsWith('projects/_/buckets/{}/objects/{}')".format(
            bucket_name, object_prefix
        )
    )
    availability_condition = downscoped.AvailabilityCondition(availability_expression)
    # Define the single access boundary rule using the above properties.
    rule = downscoped.AccessBoundaryRule(
        available_resource=available_resource,
        available_permissions=available_permissions,
        availability_condition=availability_condition,
    )
    # Define the Credential Access Boundary with all the relevant rules.
    credential_access_boundary = downscoped.CredentialAccessBoundary(rules=[rule])

    # Retrieve the source credentials via ADC.
    source_credentials, _ = google.auth.default()
    if source_credentials.requires_scopes:
        source_credentials = source_credentials.with_scopes(
            ["https://www.googleapis.com/auth/cloud-platform"]
        )

    # Create the downscoped credentials.
    downscoped_credentials = downscoped.Credentials(
        source_credentials=source_credentials,
        credential_access_boundary=credential_access_boundary,
    )

    # Refresh the tokens.
    downscoped_credentials.refresh(requests.Request())

    # These values will need to be passed to the token consumer.
    access_token = downscoped_credentials.token
    expiry = downscoped_credentials.expiry
    return (access_token, expiry)

L'esempio seguente mostra in che modo un consumer di token può fornire un gestore di aggiornamento che ottiene e aggiorna automaticamente i token con ambito ridotto:

from google.cloud import storage
from google.oauth2 import credentials

def token_consumer(bucket_name, object_name):
    """Tests token consumer readonly access to the specified object.

    Args:
        bucket_name (str): The name of the Cloud Storage bucket.
        object_name (str): The name of the object in the Cloud Storage bucket
            to read.
    """

    # Create the OAuth credentials from the downscoped token and pass a
    # refresh handler to handle token expiration. We are passing a
    # refresh_handler instead of a one-time access token/expiry pair.
    # This will allow the consumer to obtain new downscoped tokens on
    # demand every time a token is expired, without any additional code
    # changes.
    def refresh_handler(request, scopes=None):
        # The common pattern of usage is to have a token broker pass the
        # downscoped short-lived access tokens to a token consumer via some
        # secure authenticated channel.
        # For illustration purposes, we are generating the downscoped token
        # locally.
        # We want to test the ability to limit access to objects with a certain
        # prefix string in the resource bucket. object_name[0:3] is the prefix
        # here. This field is not required if access to all bucket resources are
        # allowed. If access to limited resources in the bucket is needed, this
        # mechanism can be used.
        return get_token_from_broker(bucket_name, object_prefix=object_name[0:3])

    creds = credentials.Credentials(
        None,
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
        refresh_handler=refresh_handler,
    )

    # Initialize a Cloud Storage client with the oauth2 credentials.
    storage_client = storage.Client(credentials=creds)
    # The token broker has readonly access to the specified bucket object.
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(object_name)
    print(blob.download_as_bytes().decode("utf-8"))

Scambiare e aggiornare manualmente il token di accesso

Un token broker può utilizzare l'API Security Token Service per scambiare un token di accesso con un token di accesso con ambito ridotto. Può quindi fornire il token con ambito ridotto a un consumer di token.

Per scambiare il token di accesso, utilizza il metodo HTTP e l'URL seguenti:

POST https://sts.googleapis.com/v1/token

Imposta l'intestazione Content-Type nella richiesta su application/x-www-form-urlencoded. Includi i seguenti campi nel corpo della richiesta:

Campi
grant_type

string

Utilizza il valore urn:ietf:params:oauth:grant-type:token-exchange.

options

string

Un confine di accesso alle credenziali in formato JSON, codificato con codifica percentuale.

requested_token_type

string

Utilizza il valore urn:ietf:params:oauth:token-type:access_token.

subject_token

string

Il token di accesso OAuth 2.0 che vuoi scambiare.

subject_token_type

string

Utilizza il valore urn:ietf:params:oauth:token-type:access_token.

La risposta è un oggetto JSON che contiene i seguenti campi:

Campi
access_token

string

Un token di accesso OAuth 2.0 con ambito ridotto che rispetta il confine dell'accesso alle credenziali.

expires_in

number

Il tempo fino alla scadenza del token con ambito ridotto, in secondi.

Questo campo è presente solo se il token di accesso originale rappresenta un account di servizio. Se questo campo non è presente, il token con ambito ridotto ha lo stesso periodo di scadenza del token di accesso originale.

issued_token_type

string

Contiene il valore urn:ietf:params:oauth:token-type:access_token.

token_type

string

Contiene il valore Bearer.

Ad esempio, se nel file ./access-boundary.json è archiviato un confine di accesso alle credenziali in formato JSON, puoi utilizzare il seguente comando curl per scambiare il token di accesso. Sostituisci original-token con il token di accesso originale:

curl -H "Content-Type:application/x-www-form-urlencoded" \
    -X POST \
    https://sts.googleapis.com/v1/token \
    -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token_type=urn:ietf:params:oauth:token-type:access_token&requested_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=original-token" \
    --data-urlencode "options=$(cat ./access-boundary.json)"

La risposta è simile al seguente esempio:

{
  "access_token": "ya29.dr.AbCDeFg-123456...",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "Bearer",
  "expires_in": 3600
}

Quando un consumatore di token richiede un token con ambito ridotto, il broker di token deve rispondere sia con il token con ambito ridotto che con il numero di secondi fino alla sua scadenza. Per aggiornare il token con ambito ridotto, il consumer può richiedere al broker un token con ambito ridotto prima che il token esistente scada.

Passaggi successivi