Add exmaple showing how NewTokenSource should be called.

This commit is contained in:
Patrick Jones
2021-06-10 14:55:41 -07:00
parent eb57311a00
commit add9801363
2 changed files with 45 additions and 1 deletions

View File

@@ -2,8 +2,11 @@ package downscope
import (
"context"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
@@ -54,3 +57,41 @@ func Test_DownscopedTokenSource(t *testing.T) {
t.Fatalf("Token() call failed with error %v", err)
}
}
func Example() {
ctx := context.Background()
availableResource := "//storage.googleapis.com/projects/_/buckets/foo"
availablePermissions := []string{"inRole:roles/storage.objectViewer"}
// Initializes an accessBoundary
myBoundary := AccessBoundary{make([]AccessBoundaryRule, 0)}
// Add a new rule to the AccessBoundary
myBoundary.AccessBoundaryRules = append(myBoundary.AccessBoundaryRules, AccessBoundaryRule{availableResource, availablePermissions, nil})
// Get the token source for Application Default Credentials (DefaultTokenSource is a shorthand
// for is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
// This example assumes that you've defined the GOOGLE_APPLICATION_CREDENTIALS environment variable
rootSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
log.Fatalf("failed to generate root token source; %v", err)
return
}
myTokenSource, err := NewTokenSource(context.Background(), DownscopingConfig{rootSource, myBoundary})
//myTokenSource, err := NewSource(rootSource, myBoundary)
if err != nil {
log.Fatalf("failed to generate downscoped token source: %v", err)
return
}
fmt.Printf("%+v\n", myTokenSource)
// You can now use the token held in myTokenSource to make
// Google Cloud Storage calls. A short example follows.
// storageClient, err := storage.NewClient(ctx, option.WithTokenSource(myTokenSource))
// bkt := storageClient.Bucket(bucketName)
// obj := bkt.Object(objectName)
// rc, err := obj.NewReader(ctx)
// data, err := ioutil.ReadAll(rc)
return
}