我正在尝试使用 Nuget 包建立 Google 服务器到服务器连接:
因为它是服务器到服务器,我想我需要使用“服务帐户”选项。
这是我的代码,它在最后一行失败:
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();
错误是:gmailpostmastertools 服务抛出异常。 HttpStatusCode 被禁止。调用者没有权限
您需要执行许多步骤来配置服务帐户才能使这一切正常工作。我想我已经全部完成了。
这些是我赋予服务帐户主体的角色:
我已经生成了一个密钥并下载了我在代码中使用的 json 文件。 凭证部分似乎没问题。
我还登录了管理控制台并添加了“域范围委派”。 安全 -> 访问和数据控制 -> API 控制 -> 域范围委派。 我已添加帐户服务的客户端 ID,范围为“.../auth/postmaster.readonly”。
我使用的域名(“domains/??????.com”)已在 google postmaster 页面中进行验证。
但是错误仍然表明缺少权限。
我返回的错误:
{
"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"
}
}
有人知道可能出了什么问题吗?
我发现了我犯的错误,这是在代码中,而不是 Google 中的身份验证详细信息。
对于“服务帐户”凭据,我必须添加服务帐户需要进行身份验证的用户。这是更新后的代码:
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();