Membatasi izin Cloud Storage kredensial

Halaman ini menjelaskan cara menggunakan Batas Akses Kredensial untuk memperkecil cakupan, atau membatasi, izin Identity and Access Management (IAM) yang dapat digunakan kredensial yang berlaku singkat.

Anda dapat menggunakan Batas Akses Kredensial untuk membuat token akses OAuth 2.0 yang menampilkan akun layanan, tetapi memiliki lebih sedikit izin daripada akun layanan. Contohnya, jika salah satu pelanggan Anda perlu mengakses data Cloud Storage yang Anda kontrol, Anda dapat melakukan hal berikut:

  1. Buat akun layanan yang dapat mengakses setiap bucket Cloud Storage yang Anda miliki.
  2. Buat token akses OAuth 2.0 untuk akun layanan.
  3. Terapkan Batas Akses Kredensial yang hanya mengizinkan akses ke bucket yang berisi data pelanggan Anda.

Cara kerja Batas Akses Kredensial

Untuk memperkecil cakupan izin, tentukan Batas Akses Kredensial yang menentukan resource mana yang dapat diakses oleh kredensial yang berlaku singkat, serta batas atas pada izin yang tersedia di setiap resource. Anda kemudian dapat membuat kredensial yang berlaku singkat, lalu menukarnya dengan kredensial baru yang mematuhi Batas Akses Kredensial.

Jika Anda perlu memberikan serangkaian izin yang berbeda kepada akun utama untuk setiap sesi, menggunakan Batas Akses Kredensial akan lebih efisien daripada membuat banyak akun layanan yang berbeda dan memberi setiap akun layanan serangkaian peran yang berbeda.

Contoh Batas Akses Kredensial

Bagian berikut menampilkan contoh Batas Akses Kredensial untuk kasus penggunaan umum. Anda menggunakan Batas Akses Kredensial saat menukar token akses OAuth 2.0 dengan token yang diperkecil cakupannya.

Membatasi izin untuk bucket

Contoh berikut menampilkan Batas Akses Kredensial sederhana. Hal ini berlaku untuk bucket Cloud Storage example-bucket, dan menetapkan batas atas ke izin yang disertakan dalam peran Storage Object Viewer (roles/storage.objectViewer):

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

Membatasi izin untuk beberapa bucket

Contoh berikut menunjukkan Batas Akses Kredensial yang menyertakan aturan untuk beberapa bucket:

  • Bucket Cloud Storage example-bucket-1: Untuk bucket ini, hanya izin dalam peran Storage Object Viewer (roles/storage.objectViewer) yang tersedia.
  • Bucket Cloud Storage example-bucket-2: Untuk bucket ini, hanya izin dalam peran Pembuat Storage Object (roles/storage.objectCreator) yang tersedia.
{
  "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"
      }
    ]
  }
}

Membatasi izin untuk objek tertentu

Anda juga dapat menggunakan IAM Conditions untuk menentukan objek Cloud Storage mana yang dapat diakses akun utama. Contohnya, Anda dapat menambahkan kondisi yang menyediakan izin untuk objek yang namanya diawali dengan 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')"
        }
      }
    ]
  }
}

Membatasi izin saat mencantumkan objek

Saat Anda mencantumkan objek di bucket Cloud Storage, Anda memanggil metode pada resource bucket, bukan resource objek. Akibatnya, jika suatu kondisi dievaluasi untuk permintaan daftar, dan kondisi tersebut mengacu pada nama resource, maka nama resource akan mengidentifikasi bucket, bukan objek di dalam bucket. Contohnya, saat Anda mencantumkan objek dalam example-bucket, nama resource adalah projects/_/buckets/example-bucket.

Konvensi penamaan ini dapat menyebabkan perilaku yang tidak diharapkan saat Anda mencantumkan objek. Contohnya, Anda menginginkan Batas Akses Kredensial yang mengizinkan akses tampilan ke objek di example-bucket dengan awalan customer-a/invoices/. Anda dapat mencoba menggunakan kondisi berikut di Batas Akses Kredensial:

Tidak lengkap: Kondisi yang hanya memeriksa nama resource

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

Kondisi ini berfungsi untuk membaca objek, tetapi tidak untuk mencantumkan objek:

  • Saat akun utama mencoba membaca objek dalam example-bucket dengan awalan customer-a/invoices/, kondisi akan bernilai true.
  • Saat akun utama mencoba mencantumkan objek dengan awalan tersebut, kondisi akan bernilai false. Nilai resource.name adalah projects/_/buckets/example-bucket, yang tidak dimulai dengan projects/_/buckets/example-bucket/objects/customer-a/invoices/.

Untuk mencegah masalah ini, selain menggunakan resource.name.startsWith(), kondisi Anda dapat memeriksa atribut API bernama storage.googleapis.com/objectListPrefix. Atribut ini berisi nilai parameter prefix yang digunakan untuk memfilter daftar objek. Sebagai hasilnya, Anda dapat menulis kondisi yang merujuk pada nilai parameter prefix.

Contoh berikut menunjukkan cara menggunakan atribut API dalam sebuah kondisi. Hal ini mengizinkan pembacaan dan mencantumkan objek dalam example-bucket dengan awalan customer-a/invoices/:

Lengkap: Kondisi yang memeriksa nama resource dan awalan

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

Sekarang Anda dapat menggunakan kondisi ini di Batas Akses Kredensial:

{
  "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/')"
        }
      }
    ]
  }
}

Sebelum memulai

Sebelum Anda menggunakan Batas Akses Kredensial, pastikan Anda memenuhi persyaratan berikut:

  • Anda hanya perlu memperkecil cakupan izin untuk Cloud Storage, bukan untuk layanan Google Cloud lainnya.

    Jika Anda perlu memperkecil cakupan izin untuk layanan Google Cloud tambahan, Anda dapat membuat beberapa akun layanan dan memberikan serangkaian peran yang berbeda ke setiap akun layanan.

  • Anda dapat menggunakan token akses OAuth 2.0 untuk autentikasi. Jenis kredensial yang berlaku singkat lainnya tidak mendukung Batas Akses Kredensial.

Selain itu, Anda harus mengaktifkan API yang diperlukan:

  • Enable the IAM and Security Token Service APIs.

    Enable the APIs

Membuat kredensial yang berlaku singkat yang diperkecil cakupannya

Untuk membuat token akses OAuth 2.0 dengan izin yang diperkecil cakupannya, ikuti langkah berikut:

  1. Berikan peran IAM yang tepat kepada pengguna atau akun layanan.
  2. Tentukan Batas Akses Kredensial yang menetapkan batas atas pada izin yang tersedia untuk pengguna atau akun layanan.
  3. Buat token akses OAuth 2.0 untuk akun pengguna atau layanan.
  4. Tukarkan token akses OAuth 2.0 dengan token baru yang mematuhi Batas Akses Kredensial.

Anda kemudian dapat menggunakan token akses OAuth 2.0 yang baru yang diperkecil cakupannya untuk melakukan autentikasi permintaan ke Cloud Storage.

Memberikan peran IAM

Batas Akses Kredensial menetapkan batas atas pada izin yang tersedia untuk resource. Hal tersebut dapat mengurangi izin dari akun utama, tetapi tidak dapat menambahkan izin yang belum dimiliki akun utama.

Oleh karena itu, Anda juga harus memberikan peran ke akun utama yang menyediakan izin yang mereka butuhkan, baik pada bucket Cloud Storage maupun pada resource dengan level yang lebih tinggi, seperti project.

Contohnya, Anda perlu membuat kredensial yang berlaku singkat yang diperkecil cakupannya yang mengizinkan akun layanan untuk membuat objek dalam bucket:

  • Setidaknya, Anda harus memberikan peran ke akun layanan yang menyertakan izin storage.objects.create, seperti peran Pembuat Storage Object (roles/storage.objectCreator). Batas Akses Kredensial juga harus menyertakan izin ini.
  • Anda juga dapat memberikan peran yang mencakup lebih banyak izin, seperti peran Admin Storage Object (roles/storage.objectAdmin). Akun layanan hanya dapat menggunakan izin yang muncul dalam pemberian peran dan Batas Akses Kredensial.

Untuk mempelajari peran bawaan untuk Cloud Storage, lihat Peran Cloud Storage.

Komponen Batas Akses Kredensial

Batas Akses Kredensial adalah objek yang berisi daftar aturan batas akses. Setiap aturan berisi informasi berikut:

  • Resource tempat aturan diterapkan.
  • Batas atas izin yang tersedia pada resource tersebut.
  • Opsional: Kondisi yang membatasi izin lebih lanjut. Kondisi mencakup hal berikut:
    • Ekspresi kondisi yang bernilai true atau false. Jika bernilai true, akses akan diizinkan; jika tidak, akses akan ditolak.
    • Opsional: Judul yang mengidentifikasi kondisi.
    • Opsional: Deskripsi yang berisi informasi selengkapnya tentang kondisi tersebut.

Jika Anda menerapkan Batas Akses Kredensial ke kredensial yang berlaku singkat, maka kredensial hanya dapat mengakses resource di Batas Akses Kredensial. Tidak ada izin yang tersedia di resource lain.

Batas Akses Kredensial dapat berisi hingga 10 aturan batas akses. Anda hanya dapat menerapkan satu Batas Akses Kredensial untuk setiap kredensial yang berlaku singkat.

Saat ditampilkan sebagai objek JSON, Batas Akses Kredensial berisi kolom berikut:

Kolom
accessBoundary

object

Wrapper untuk Batas Akses Kredensial.

accessBoundary.accessBoundaryRules[]

object

Daftar aturan batas akses untuk diterapkan ke kredensial yang berlaku singkat.

accessBoundary.accessBoundaryRules[].availablePermissions[]

string

Daftar yang menentukan batas atas pada izin yang tersedia untuk resource.

Setiap nilai adalah ID untuk peran bawaan atau peran khusus IAM, dengan awalan inRole:. Contoh: inRole:roles/storage.objectViewer. Hanya izin dalam peran ini yang akan tersedia.

accessBoundary.accessBoundaryRules[].availableResource

string

Nama lengkap resource bucket Cloud Storage tempat aturan diterapkan. Gunakan format //storage.googleapis.com/projects/_/buckets/bucket-name.

accessBoundary.accessBoundaryRules[].availabilityCondition

object

Opsional. Kondisi yang membatasi ketersediaan izin untuk objek Cloud Storage tertentu.

Gunakan kolom ini jika Anda ingin menyediakan izin untuk objek tertentu, bukan semua objek dalam bucket Cloud Storage.

accessBoundary.accessBoundaryRules[].availabilityCondition.expression

string

Ekspresi kondisi yang menentukan objek Cloud Storage yang izinnya tersedia.

Untuk mempelajari cara merujuk ke objek tertentu dalam ekspresi kondisi, lihat atribut resource.name.

accessBoundary.accessBoundaryRules[].availabilityCondition.title

string

Opsional. String pendek yang mengidentifikasi tujuan kondisi.

accessBoundary.accessBoundaryRules[].availabilityCondition.description

string

Opsional. Detail tentang tujuan kondisi.

Untuk contoh dalam format JSON, lihat Contoh Batas Akses Kredensial di halaman ini.

Membuat token akses OAuth 2.0

Sebelum membuat kredensial yang berlaku singkat yang diperkecil cakupannya, Anda harus membuat token akses OAuth 2.0 normal. Kemudian, Anda dapat menukar kredensial normal dengan kredensial yang diperkecil cakupannya. Saat Anda membuat token akses, gunakan https://www.googleapis.com/auth/cloud-platform cakupan OAuth 2.0.

Untuk membuat token akses untuk akun layanan, Anda dapat menyelesaikan alur OAuth 2.0 server ke server, atau menggunakan Service Account Credentials API untuk membuat token akses OAuth 2.0.

Untuk membuat token akses bagi pengguna, lihat Mendapatkan token akses OAuth 2.0. Anda juga dapat menggunakan Playground OAuth 2.0 untuk membuat token akses untuk Akun Google Anda sendiri.

Menukarkan token akses OAuth 2.0

Setelah membuat token akses OAuth 2.0, Anda dapat menukar token akses tersebut dengan token yang diperkecil cakupannya yang mematuhi Batas Akses Kredensial. Proses ini biasanya melibatkan broker token dan konsumen token:

  • Broker token bertanggung jawab menentukan Batas Akses Kredensial dan menukar token akses untuk token yang diperkecil cakupannya.

    Broker token dapat menggunakan library autentikasi yang didukung untuk menukar token akses secara otomatis, atau memanggil Layanan Token Keamanan untuk menukar token secara manual.

  • Konsumen token meminta token akses yang diperkecil cakupannya dari broker token, lalu menggunakan token akses yang diperkecil cakupannya untuk melakukan tindakan lain.

    Konsumen token dapat menggunakan library autentikasi yang didukung untuk memuat ulang token akses secara otomatis sebelum masa berlakunya habis. Selain itu, konsumen token dapat memuat ulang token secara manual, atau membiarkan masa berlaku token habis tanpa memuat ulang token tersebut.

Menukar dan memuat ulang token akses secara otomatis

Jika Anda membuat broker token dan konsumen token dengan salah satu bahasa berikut, Anda dapat menggunakan library autentikasi Google untuk menukar dan memuat ulang token secara otomatis:

Go

Untuk Go, Anda dapat menukar dan memuat ulang token secara otomatis dengan versi v0.0.0-20210819190943-2bc19b11175f atau yang lebih baru dari paket golang.org/x/oauth2.

Untuk memeriksa versi mana dari paket ini yang Anda gunakan, jalankan perintah berikut dalam direktori aplikasi Anda:

go list -m golang.org/x/oauth2

Contoh berikut menunjukkan bagaimana broker token dapat membuat token yang diperkecil cakupannya:


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
}

Contoh berikut menunjukkan bagaimana konsumen token dapat menggunakan pengendali refresh untuk secara otomatis memperoleh dan memuat ulang token yang diperkecil cakupannya:


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

Untuk Java, Anda dapat menukar dan memuat ulang token secara otomatis dengan com.google.auth:google-auth-library-oauth2-http artefak versi 1.1.0 atau yang lebih baru.

Untuk memeriksa versi mana dari artefak ini yang Anda gunakan, jalankan perintah Maven berikut di direktori aplikasi Anda:

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

Contoh berikut menunjukkan bagaimana broker token dapat membuat token yang diperkecil cakupannya:

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;
}

Contoh berikut menunjukkan bagaimana konsumen token dapat menggunakan pengendali refresh untuk secara otomatis memperoleh dan memuat ulang token yang diperkecil cakupannya:

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

Untuk Node.js, Anda dapat menukar dan memuat ulang token secara otomatis dengan paket google-auth-library versi 7.9.0 atau yang lebih baru.

Untuk memeriksa versi mana dari paket ini yang Anda gunakan, jalankan perintah berikut dalam direktori aplikasi Anda:

npm list google-auth-library

Contoh berikut menunjukkan bagaimana broker token dapat membuat token yang diperkecil cakupannya:

// 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;
}

Contoh berikut menunjukkan bagaimana konsumen token dapat menyediakan pengendali refresh yang secara otomatis memperoleh dan memuat ulang token yang diperkecil cakupannya:

// 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

Untuk Python, Anda dapat menukar dan memuat ulang token secara otomatis dengan paket google-auth versi 2.0.0 atau yang lebih baru.

Untuk memeriksa versi mana dari paket ini yang Anda gunakan, jalankan perintah berikut di lingkungan tempat paket diinstal:

pip show google-auth

Contoh berikut menunjukkan bagaimana broker token dapat membuat token yang diperkecil cakupannya:

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)

Contoh berikut menunjukkan bagaimana konsumen token dapat menyediakan pengendali refresh yang secara otomatis memperoleh dan memuat ulang token yang diperkecil cakupannya:

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"))

Menukar dan memperbarui token akses secara manual

Broker token dapat menggunakan API Layanan Token Keamanan untuk menukar token akses dengan token akses yang diperkecil cakupannya. Broker token kemudian dapat menyediakan token yang diperkecil cakupannya kepada konsumen token.

Untuk menukar token akses, gunakan metode HTTP dan URL berikut:

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

Tetapkan header Content-Type dalam permintaan menjadi application/x-www-form-urlencoded. Sertakan kolom berikut dalam isi permintaan:

Kolom
grant_type

string

Gunakan nilai urn:ietf:params:oauth:grant-type:token-exchange.

options

string

Batas Akses Kredensial format JSON, dienkode dengan encoding persen.

requested_token_type

string

Gunakan nilai urn:ietf:params:oauth:token-type:access_token.

subject_token

string

Token akses OAuth 2.0 yang ingin Anda tukarkan.

subject_token_type

string

Gunakan nilai urn:ietf:params:oauth:token-type:access_token.

Responsnya adalah objek JSON yang berisi kolom berikut:

Kolom
access_token

string

Token akses OAuth 2.0 yang diperkecil cakupannya yang mematuhi Batas Akses Kredensial.

expires_in

number

Jumlah waktu hingga token yang diperkecil cakupannya berakhir, dalam detik.

Kolom ini hanya ada jika token akses asli menampilkan akun layanan. Jika kolom ini tidak ada, token yang diperkecil cakupannya akan memiliki waktu yang sama dengan masa berlaku token akses asli.

issued_token_type

string

Berisi nilai urn:ietf:params:oauth:token-type:access_token.

token_type

string

Berisi nilai Bearer.

Contohnya, jika Batas Akses Kredensial format JSON disimpan dalam file ./access-boundary.json, Anda dapat menggunakan perintah curl berikut untuk menukar token akses. Ganti original-token dengan token akses asli:

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)"

Responsnya mirip dengan contoh berikut:

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

Saat konsumen token meminta token yang diperkecil cakupannya, broker token harus merespons dengan token yang diperkecil cakupannya dan jumlah detik hingga masa berlakunya habis. Untuk memuat ulang token yang diperkecil cakupannya, konsumen dapat meminta token yang diperkecil cakupannya dari broker sebelum masa berlaku token yang ada habis.

Langkah selanjutnya