Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Created November 15, 2024 13:45
Show Gist options
  • Save salrashid123/7c1d1425afdee2ba5f07a015b1562628 to your computer and use it in GitHub Desktop.
Save salrashid123/7c1d1425afdee2ba5f07a015b1562628 to your computer and use it in GitHub Desktop.
Google WorkloadFederation SubjectTokenSupplier sample
/*
simple example of https://pkg.go.dev/golang.org/x/oauth2/google/externalaccount#SubjectTokenSupplier
also see https://github.com/salrashid123/gcp_aws_web_identity
*/
package main
import (
"context"
"flag"
"log"
"cloud.google.com/go/storage"
"golang.org/x/oauth2/google/externalaccount"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
var (
projectId = flag.String("projectId", "core-eso", "ProjectID")
bucket = flag.String("bucket", "core-eso-bucket", "GCS Bucket")
)
type subjectTokenSupplier struct {
param1 string
}
func NewSubjectTokenProvider(r string) (subjectTokenSupplier, error) {
return subjectTokenSupplier{
param1: r,
}, nil
}
func (supp subjectTokenSupplier) SubjectToken(ctx context.Context, options externalaccount.SupplierOptions) (string, error) {
return "eyJhbGciOiJSUzI1NiIsImt...you_id_token", nil
}
func main() {
flag.Parse()
ctx := context.Background()
ac, err := NewSubjectTokenProvider("foo")
if err != nil {
log.Fatal(err)
}
ts, err := externalaccount.NewTokenSource(ctx, externalaccount.Config{
Audience: "//iam.googleapis.com/projects/995081019036/locations/global/workloadIdentityPools/fake-oidc-pool-1/providers/fake-oidc-provider-1",
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
SubjectTokenSupplier: ac,
})
if err != nil {
log.Fatal(err)
}
storageClient, err := storage.NewClient(ctx, option.WithTokenSource(ts))
if err != nil {
log.Fatal(err)
}
it := storageClient.Bucket(*bucket).Objects(ctx, nil)
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Bucket(%s).Objects: %v\n", *bucket, err)
}
log.Println(attrs.Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment