Skip to content

Instantly share code, notes, and snippets.

@kostyay
Last active November 29, 2022 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostyay/7aace560cc0888b1a6cff889342ac55a to your computer and use it in GitHub Desktop.
Save kostyay/7aace560cc0888b1a6cff889342ac55a to your computer and use it in GitHub Desktop.
[Golang] Use google admin sdk from service account impersonating as user #adminsdk
// It took me few hours how to get this to work
// Have a service account in GCP which wanted to use Admin SDK with Google Workspace
// The service account needs to have the following role: `roles/iam.serviceAccountTokenCreator`
// You need to create a domain wide delegation for the service account client id
import (
"google.golang.org/api/impersonate"
"google.golang.org/api/option"
"context"
)
func main() {
ctx := context.Background()
// // Base credentials sourced from ADC or provided client options.
ts, err := impersonate.CredentialsTokenSource(
ctx,
impersonate.CredentialsConfig{
TargetPrincipal: "service-account@your-google-project.com", // this is the *service account*
Scopes: []string{admin.AdminDirectoryGroupReadonlyScope, admin.AdminDirectoryUserReadonlyScope}, // the scopes you want to obtain
Subject: "user@google-workspace.com", // service accounts impersonate as a *user* in the google workspace, so you must enter an email here
})
adminService, err := admin.NewService(context.Background(), option.WithTokenSource(ts))
if err != nil {
return nil, err
}
res, err := a.adminService.Groups.List().Context(ctx)
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment