我试图更新Google Sheets中的行,但出现错误403
请求的身份验证作用域不足。[403]错误[Message[请求的身份验证作用域不足。]位置[-]原因[禁止]域[全局]]
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,
});
List<object> list1 = new List<object>() { "Item", "Cost", "Stocked", "Ship Date" };
List<object> list2 = new List<object>() { "Wheel", "$20.50", "4", "3/1/2016" };
List<object> list3 = new List<object>() { "Door", "$15", "2", "3/15/2016" };
List<object> list4 = new List<object>() { "Engine", "$100", "1", "30/20/2016" };
List<object> list5 = new List<object>() { "Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)" };
IList<IList<Object>> list = new List<IList<Object>>() { list1, list2, list3, list4, list5 };
ValueRange VRange = new ValueRange();
VRange.Range = range;
VRange.Values = list;
SpreadsheetsResource.ValuesResource.UpdateRequest upd = service.Spreadsheets.Values.Update(VRange, spreadsheetId, range);
UpdateValuesResponse response = upd.Execute();
Console.WriteLine(response.UpdatedRows);
Google缓存验证,因此一旦您通过浏览器弹出窗口批准客户端,它就不会再次出现。然而,当你更改它不检查的范围时,它只是继续使用已经批准(存储)的凭据,无论以前的权限是什么。
示例代码确实在注释中提到了这一点:
如果修改这些作用域,请删除以前保存的凭据访问~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
由于您正在向System.Environment.SpecialFolder.Personal
写入,它将显示在您的/Documents文件夹中,每个Path.Combine
的.credentials/sheets.googleapis.com-dotnet-quickstart.json
下。删除该文件(或者文件夹,如果你喜欢的话)并确保使用static string[] Scopes = { SheetsService.Scope.Spreadsheets };
,它现在会再次提示你,你应该已经做好了准备。
我看不到您在代码中定义Scopes的行,但请确保您没有请求READONLY范围