Leo
Leo

Reputation: 45

Google Postmaster API

I'm trying to set up a Google server-to-server connection with the Nuget packages:

Because it is server-to-server I think I need to use the "Service Account" option.

This is the code that I have and it fails on the last line:

var credential = GoogleCredential.FromFile("path\\to\file\\boreal-dock-34534534534.json")
.CreateScoped(new[] { "https://www.googleapis.com/auth/postmaster.readonly" });

// Google.Apis.PostmasterTools.v1.PostmasterToolsService.
var service = new PostmasterToolsService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "C9Transact",
});

ListTrafficStatsResponse response = await service.Domains.TrafficStats.List("domains/domain.com").ExecuteAsync();

The error is: The service gmailpostmastertools has thrown an exception. HttpStatusCode is Forbidden. The caller does not have permission

There are so many steps you have to do to configure the Service Account to make this all work. I think I have done them all.

These are the Roles that I have given to the principal of the Service Account:

I have generated a key and download the json file which I use in the code. And the credential part seem to be ok.

I also logged into the admin console and added the "Domain-wide Delegation". Security -> Access and data control -> API Controls -> Domain-wide Delegation. I have added the client ID of the Account Service with as scope ".../auth/postmaster.readonly".

The domain ("domains/????.com") that I'm using is verified in the google postmaster page.

But the error still indicates that there is a permission missing.

Error that I'm getting back:

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

Is there anybody that has an idea what could be wrong?

Upvotes: 0

Views: 421

Answers (1)

Leo
Leo

Reputation: 45

I found out the mistake that I made and this was in the code not with the authentication details in Google.

For "Service Account" Credentials I had to add a user that the Service account needs to do the authentication with. Here is the updated code:

var credential = GoogleCredential.FromFile("path\\to\file\\boreal-dock-34534534534.json")
.CreateScoped(new[] { "https://www.googleapis.com/auth/postmaster.readonly" }); 


if (credential.UnderlyingCredential is ServiceAccountCredential)
{
    // Specify the user you are impersonating in the domain
    credential = credential.CreateWithUser("???@?????.com");
}

var service = new PostmasterToolsService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "C9Transact",
});

ListTrafficStatsResponse response = await service.Domains.TrafficStats.List("domains/????.com").ExecuteAsync();

Upvotes: 0

Related Questions