golang.org/x/oauth2@v0.18.0/google/downscope/tokenbroker_test.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package downscope_test 6 7 import ( 8 "context" 9 "fmt" 10 11 "golang.org/x/oauth2/google" 12 13 "golang.org/x/oauth2" 14 "golang.org/x/oauth2/google/downscope" 15 ) 16 17 func ExampleNewTokenSource() { 18 // This shows how to generate a downscoped token. This code would be run on the 19 // token broker, which holds the root token used to generate the downscoped token. 20 ctx := context.Background() 21 // Initializes an accessBoundary with one Rule which restricts the downscoped 22 // token to only be able to access the bucket "foo" and only grants it the 23 // permission "storage.objectViewer". 24 accessBoundary := []downscope.AccessBoundaryRule{ 25 { 26 AvailableResource: "//storage.googleapis.com/projects/_/buckets/foo", 27 AvailablePermissions: []string{"inRole:roles/storage.objectViewer"}, 28 }, 29 } 30 31 var rootSource oauth2.TokenSource 32 // This Source can be initialized in multiple ways; the following example uses 33 // Application Default Credentials. 34 35 rootSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform") 36 37 dts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary}) 38 if err != nil { 39 fmt.Printf("failed to generate downscoped token source: %v", err) 40 return 41 } 42 43 tok, err := dts.Token() 44 if err != nil { 45 fmt.Printf("failed to generate token: %v", err) 46 return 47 } 48 _ = tok 49 // You can now pass tok to a token consumer however you wish, such as exposing 50 // a REST API and sending it over HTTP. 51 52 // You can instead use the token held in dts to make 53 // Google Cloud Storage calls, as follows: 54 55 // storageClient, err := storage.NewClient(ctx, option.WithTokenSource(dts)) 56 57 }