3

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.

KadoBOT
  • 2,944
  • 4
  • 16
  • 34
  • It looks like your subject that the service account is impersonating is a service account and not a user or admin. Also the service account used needs to have Domain Wide Delegation to be able to impersonate a user in the domain. – Aerials Mar 11 '21 at 14:17
  • Hi Aerials, I tried with a user as well (email@domain.com) and the service account has Domain Wide Delegation enabled (with the `AdminReportsAuditReadonlyScope` role on it). Although in the Domain Wide Delegation settings the ID refers to the service account, is this correct? – KadoBOT Mar 11 '21 at 14:22

1 Answers1

3

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"
KadoBOT
  • 2,944
  • 4
  • 16
  • 34
  • would you mind to share the full code for this. I'm stuck can't find how to achive this – Axel Aug 19 '21 at 21:36
  • 1
    Sure, but there's not much difference from the code above: https://play.golang.org/p/MsPMZLr9EoU – KadoBOT Aug 21 '21 at 06:31
  • What if I'm using environment provided account instead of exact json file? I mean when running on GCP you should not generate json keys. – Mistic92 Jan 27 '22 at 15:22