gogoogle-cloud-platformgoogle-admin-sdkgoogle-reporting-api

How to impersonate user using Go Google SDK?


I have a user which I use to query the Reports API. I generated the token and read the credentials using the google.ConfigFromJSON method.

Although, now I need to do the same, but instead of a user, I need to use a service account. And accordingly to the documentation, I need to impersonate a user as it's not possible to call the API using a service account (correct me if I'm wrong).

This is what I did to impersonate the user:

impersonatedOption := option.ImpersonateCredentials("user@project.iam.gserviceaccount.com")
credsOption := option.WithCredentialsFile("cert.json")
scopesOption := option.WithScopes(admin.AdminReportsAuditReadonlyScope)

httpClient, _, err := transport.NewHTTPClient(ctx,  scopesOption, credsOption, impersonatedOption)

srv, err := admin.NewService(ctx, option.WithHTTPClient(httpClient))

But no success:

Get "https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/login?alt=json&eventName=account_disabled_spamming&prettyPrint=false": impersonate: status code 403: 
{
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "status": "PERMISSION_DENIED"
  }
}

The service account is configured as a SuperAdmin and should have all permissions.


Solution

  • I just needed to load the cert, and set the Subject to be able to impersonate the user:

        config, err := google.JWTConfigFromJSON(b, scope...)
        config.Subject = "impersonated_user@email.com"