Request had insufficient authentication scopes [40

2019-07-10 02:35发布

问题:

In Google Developer Consol the Sheet API is enabled. I am using the same key I use to access spreadsheet.When I read data all work fine. I get a Request had insufficient authentication scopes error on the 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();
        }
    }
}

回答1:

I had run and application before with another scope.

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

The ploblem was that Credentionals was same cause it had stored in file. I am not sure why cretendionals wasn't rewrite each time when i run an application, but when I comment line with additional parametr FileDataStore code was working as expected.

        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);

            }         


回答2:

You can change the initialisation code so it load the file everytime

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);
}


回答3:

  1. Firstly delete the credentials files /Users/{YOUR_USER_NAME}/.credentials/sheets.googleapis.com-dotnet-quickstart.json (depending on your setting)

  2. Change the scope variable used for reading cells from Google Spreadsheets from

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

to

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

  1. After execution of code, API will authenticate again and then issue will be resolved.