...

Source file src/cloud.google.com/go/auth/credentials/downscope/example_test.go

Documentation: cloud.google.com/go/auth/credentials/downscope

     1  // Copyright 2023 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package downscope_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  
    21  	"cloud.google.com/go/auth/credentials"
    22  	"cloud.google.com/go/auth/credentials/downscope"
    23  )
    24  
    25  func ExampleNewCredentials() {
    26  	// This shows how to generate a downscoped token. This code would be run on
    27  	// the token broker, which holds the root token used to generate the
    28  	// downscoped token.
    29  	ctx := context.Background()
    30  
    31  	// Initializes an accessBoundary with one Rule which restricts the
    32  	// downscoped token to only be able to access the bucket "foo" and only
    33  	// grants it the permission "storage.objectViewer".
    34  	accessBoundary := []downscope.AccessBoundaryRule{
    35  		{
    36  			AvailableResource:    "//storage.googleapis.com/projects/_/buckets/foo",
    37  			AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
    38  		},
    39  	}
    40  
    41  	// This Source can be initialized in multiple ways; the following example uses
    42  	// Application Default Credentials.
    43  	baseProvider, err := credentials.DetectDefault(&credentials.DetectOptions{
    44  		Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
    45  	})
    46  	creds, err := downscope.NewCredentials(&downscope.Options{Credentials: baseProvider, Rules: accessBoundary})
    47  	if err != nil {
    48  		fmt.Printf("failed to generate downscoped token provider: %v", err)
    49  		return
    50  	}
    51  
    52  	tok, err := creds.Token(ctx)
    53  	if err != nil {
    54  		fmt.Printf("failed to generate token: %v", err)
    55  		return
    56  	}
    57  	_ = tok
    58  	// You can now pass tok to a token consumer however you wish, such as exposing
    59  	// a REST API and sending it over HTTP.
    60  
    61  	// You can instead use the token held in tp to make
    62  	// Google Cloud Storage calls, as follows:
    63  	// storageClient, err := storage.NewClient(ctx, option.WithTokenProvider(tp))
    64  }
    65  

View as plain text