oauth2/google/downscope/example_test.go

44 lines
1.3 KiB
Go
Raw Normal View History

2021-06-22 12:25:17 -04:00
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package downscope_test
import (
"context"
2021-07-29 16:38:18 -04:00
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google/downscope"
)
func ExampleNewTokenSource() {
ctx := context.Background()
2021-06-22 12:25:17 -04:00
// Initializes an accessBoundary with one Rule.
accessBoundary := []downscope.AccessBoundaryRule{
2021-06-22 12:25:17 -04:00
{
AvailableResource: "//storage.googleapis.com/projects/_/buckets/foo",
AvailablePermissions: []string{"inRole:roles/storage.objectViewer"},
},
}
var rootSource oauth2.TokenSource
// This Source can be initialized in multiple ways; the following example uses
// Application Default Credentials.
// rootSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
2021-06-24 19:24:14 -04:00
dts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
if err != nil {
2021-07-29 16:38:18 -04:00
fmt.Printf("failed to generate downscoped token source: %v", err)
2021-06-24 19:24:14 -04:00
}
2021-07-29 16:38:18 -04:00
// Enables automatic token refreshing
_ = oauth2.ReuseTokenSource(nil, dts)
2021-07-29 16:38:18 -04:00
// You can now use the token held in myTokenSource to make
// Google Cloud Storage calls, as follows:
// storageClient, err := storage.NewClient(ctx, option.WithTokenSource(myTokenSource))
}