更新单元格电子表格时,请求的认证范围[403]不足

时间:2016-08-21 16:24:17

标签: c# google-api google-api-dotnet-client

在Google Developer Consol中,启用了Sheet API。我使用的是用于访问电子表格的相同密钥。当我读取数据时,所有工作都正常。我在requestUp.Execute()上获得了一个请求,认证范围不足。

using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.Sheets.v4;
using System.IO;
using System.Threading;


namespace SpreadSheetTest
{
    class Program
    {
        static string[] Scopes = { SheetsService.Scope.Spreadsheets };
        static string ApplicationName = "Google Sheets API .NET Quickstart";
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                 new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);

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

            // Define request parameters.
            String spreadsheetId = "165WwBrowehv2FGzt3xUjAkyKeU2IKdQzQZ9gyaGNzV0";
            String range = "sheet1!A2:E2";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);


            ValueRange response = request.Execute();



            BatchUpdateValuesRequest body = new BatchUpdateValuesRequest();
            List<ValueRange> rangev = new List<ValueRange>();
            ValueRange vv = new ValueRange();
            vv.Range = "sheet1!A2:E2";
            IList<IList<object>> values = new List<IList<object>>();
            List<object> child = new List<object>();
            for (int i = 0; i < 5; i++)
            {
                child.Add(i);
            }
            values.Add(child);
            vv.Values = values;
            rangev.Add(vv);
            body.Data = rangev;

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest requestUp =
                    service.Spreadsheets.Values.BatchUpdate(body, spreadsheetId);
            var result = requestUp.Execute();
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我之前用另一个范围运行和申请。

static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadOnly };

问题是Credentionals是相同的,因为它存储在文件中。我不确定为什么每次运行应用程序时都没有重写cretendionals,但是当我使用额外的参数FileDataStore代码注释时,代码按预期工作。

        static string ApplicationName = "Google Sheets API .NET Quickstart";
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                 new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None
                //,new FileDataStore(credPath, true)
                ).Result;
                Console.WriteLine("Credential file saved to: " + credPath);

            }         

答案 1 :(得分:0)

您可以更改初始化代码,以便每次加载文件

var filePath = @"path-to-file.json";

GoogleCredential credential;
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
    credential = GoogleCredential.FromStream(stream);
    credential = credential.CreateScoped(scopes);
}

答案 2 :(得分:0)

  1. 首先删除凭据文件/Users/{YOUR_USER_NAME}/.credentials/sheets.googleapis.com-dotnet-quickstart.json(取决于您的设置)

  2. 更改用于从Google电子表格中读取单元格的范围变量

  3.   

    static string [] Scopes = {SheetsService.Scope.SpreadsheetsReadonly};

      

    static string [] Scopes = {SheetsService.Scope.Spreadsheets};

    1. 执行代码后,API将再次进行身份验证,然后问题将得到解决。