Delegate domain-wide authority using Golang
- 2 minutes read - 230 wordsI’d not used Google’s Domain-wide Delegation from Golang and struggled to find example code.
Google provides Java and Python samples.
Google has a myriad packages implementing its OAuth security and it’s always daunting trying to determine which one to use.
As it happens, I backed into the solution through client.Options
ctx := context.Background()
// Google Workspace APIS don't use IAM do use OAuth scopes
// Scopes used here must be reflected in the scopes on the
// Google Workspace Domain-wide Delegate client
scopes := []string{ ... }
// Delegates on behalf of this Google Workspace user
subject := "a@google-workspace-email.com"
creds, _ := google.FindDefaultCredentialsWithParams(
ctx,
google.CredentialsParams{
Scopes: scopes,
Subject: subject,
},
)
opts := option.WithCredentials(creds)
service, _ := admin.NewService(ctx, opts)
In this case NewService applies to Google’s Golang Admin SDK API although the pattern of NewService(ctx) or NewService(ctx, opts) where opts is a option.ClientOption is consistent across Google’s Golang libraries.
The Admin SDK documentation cites Other authentication options, does not include an example for Domain-wide Delegation but has option.WithScopes(...), option.WithTokenSource etc. and so seemed fruitful.
option.WithCredentials expects google.Credentials narrowing down the correct package to use and this includes methods that I’m familiar with google.CredentialsFromJSON and google.FindDefaultCredentials.
I noticed google.FindDefaultCredentialsWithParams but conveniently its parameter’s type CredentialsParams was documented immediately beneath it (otherwise I may have moved on) and it includes Subject and “Subject is the user email used for domain wide delegation”.