oauth2/google/downscope/example_test.go
Patrick Jones 6f1e639406 google/downscope: update documentation
Change-Id: Ib4dfc7b554c1e7565cc61bc372a98ddd390e7453
GitHub-Last-Rev: 63894e56810431f8a45d381f4ffb123da1a1b8e0
GitHub-Pull-Request: golang/oauth2#512
Reviewed-on: https://go-review.googlesource.com/c/oauth2/+/338389
Reviewed-by: Cody Oss <codyoss@google.com>
Reviewed-by: Chris Broadfoot <cbro@golang.org>
Trust: Cody Oss <codyoss@google.com>
Trust: Chris Broadfoot <cbro@golang.org>
Run-TryBot: Cody Oss <codyoss@google.com>
Run-TryBot: Chris Broadfoot <cbro@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
2021-08-05 13:40:26 +00:00

45 lines
1.3 KiB
Go

// 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"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google/downscope"
)
func ExampleNewTokenSource() {
ctx := context.Background()
// Initializes an accessBoundary with one Rule.
accessBoundary := []downscope.AccessBoundaryRule{
{
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")
dts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: rootSource, Rules: accessBoundary})
if err != nil {
fmt.Printf("failed to generate downscoped token source: %v", err)
return
}
// Enables automatic token refreshing
_ = oauth2.ReuseTokenSource(nil, dts)
// 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))
}