【问题标题】:Google service account not being authorized for calendar APIGoogle 服务帐户未获得日历 API 的授权
【发布时间】:2018-09-03 02:13:39
【问题描述】:

我正在尝试通过服务帐户连接到我们 G Suite 域中的所有日历。

我创建了一个新项目并在 API 和服务页面中启用了 Google Calendar API。

我创建了一个 Google 服务帐户:

  • 一个名字
  • 似乎适用的角色
  • 生成的 json 密钥文件
  • 为整个域启用 G Suite

在服务帐户管理页面中,我获取了我的 ID (AAA@BBB.iam.gserviceaccount.com)

我进入 G Suite 安全模块并进入 ManageOauthClients 页面,在该页面中输入 ID 并选择了谷歌日历 API (https://www.googleapis.com/auth/calendar)

它正确识别了我的 ID 并添加了:

1234567890 日历(读写)https://www.googleapis.com/auth/calendar

其中 1234567890 是 Google 从我的 AAA@BBB.iam.gserviceaccount.com 输入中获取的 ID。

现在我为 Google 和日历 API 添加了 nuget 包,并在 C# 命令行应用程序中编写了以下代码:

        var scopes = new[] { CalendarService.Scope.Calendar };

        ServiceAccountCredential credential;

        using (Stream stream = new FileStream("ToprServiceAccount-xxxxyyyyy.json", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = GoogleCredential.FromStream(stream).CreateScoped(scopes).UnderlyingCredential as ServiceAccountCredential;
        }

        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });

        var list = service.CalendarList.Get("planning@mydomain.com").Execute();

我确保我要求的日历存在。它是我用来实际执行上述所有步骤的帐户中的一个。

但我仍然收到 404 错误,这意味着我很可能没有访问(我自己的)日历的权限。

可能与角色有关吗?我不确定在创建服务帐号时要选择什么角色。

此外,当只是尝试获取所有日历的列表时,它是一个空列表。

【问题讨论】:

    标签: c# google-api google-authentication google-workspace


    【解决方案1】:

    我发现出了什么问题(来源:https://neal.codes/blog/google-calendar-api-on-g-suite/

    在 G-Suite -> 应用程序 -> 日历 -> 常规设置中,我必须启用共享所有日历的选项,并且外部人可以更改日历

    进入任何日历并与服务帐户电子邮件共享日历后。根据我在问题中的示例,那将是 AAA@BBB.iam.gserviceaccount.com。

    据我所知,这两个步骤在文档中没有提到。很高兴我现在可以使用它!

    【讨论】:

      【解决方案2】:

      我想说检查您是否在 G Suite 的 ManageOauthClients 部分中使用了正确的客户端 ID。服务帐户电子邮件中的 ID 应与您需要使用的客户 ID 不同。

      您可以通过两种方式确认您拥有正确的客户 ID:

      1. 转到生成的 JSON 密钥文件。您可以通过查看client_id 键值对来获取客户端 ID
      2. 在 Cloud Console 中,转到 IAM 和管理 -> 服务帐号。最后一列应该是Options。如果您已为该帐户配置域范围委派 (DwD),则应单击 View Client ID,这会将您带到另一个屏幕,您可以在其中查看您的客户 ID。

      【讨论】:

      • 我检查了两者,它们匹配。还验证了它在 ManageOauthClients 部分中的设置是否正确
      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2020-08-03
      • 1970-01-01
      相关资源
      最近更新 更多