【问题标题】:Using .Net to access Google Sheets with a service account generates a "The caller does not have permission [403]" error使用 .Net 通过服务帐户访问 Google 表格会生成“调用者没有权限 [403]”错误
【发布时间】:2019-04-02 15:33:25
【问题描述】:

我正在使用 .Net(并且我已安装 NuGet 包)使用服务帐户访问 Google 表格。我有一个 Google API 帐户,创建了服务帐户,甚至还有一个可以使用的测试表。我已经包含了 JSON 文件,该文件描述了我从我创建的服务帐户下载的凭据。一切似乎都正常,除了当我使用 Execute 方法调用时,我收到以下错误:

调用者没有权限[403]消息[调用者没有权限 有权限] Location[-] Reason[forbidden] Domain[global]

Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__34.MoveNext()

我也为服务帐户开启了全局访问,但仍然无法使用。我尝试与工作表共享服务帐户,但似乎没有任何方法可以做到这一点。

我的代码如下所示:

string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
string ApplicationName = "My Unit Test";

GoogleCredential sac;

        using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
        {
            sac = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
        }


// Create Google Sheets API service.
        var service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = sac,
            ApplicationName = ApplicationName,
        });

String spreadsheetId = "1_aeTu4YxDKrqDBvCNR1awyo_7WDha0JBVo1jLxsz3pA";
        String range = "Export!A2:E";
        SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);

ValueRange response = request.Execute(); // Exception thrown here

我需要执行才能成功登录并访问我设置的 Google 表格。有没有人看到这个或知道解决方法?

【问题讨论】:

    标签: .net api service google-sheets account


    【解决方案1】:

    没有人回应,我自己找到了解决办法。我用于测试的 gmail 帐户是一个专门的工作域。它不允许我正确共享工作表。所以,我设置了一个新的谷歌帐户,添加了所有的 apis 和服务帐户。为服务帐户添加了适当的角色。生成了新的 json 私钥。使用该新帐户创建了一个工作表并与新服务帐户共享它......它有效。重要提示,您必须与服务帐户共享工作表,否则将无法使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 2022-07-18
      • 2019-03-30
      • 2021-04-06
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多