【发布时间】:2021-01-19 16:18:10
【问题描述】:
每个人。
我编写了一个 C# 项目,它可以读取/写入谷歌表格,它工作正常。 最近我更换了台式机,因此将我的程序移入其中。 当我启动程序时,出现以下错误。
Google.Apis.Auth.OAuth2.Responses.TokenResponseException
HResult=0x80131500
Message=Error:"invalid_grant", Description:"Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.", Uri:""
Source=Google.Apis.Auth
我认为它的凭据可能是错误的,因为我的新机器。 所以我通过参考这个网站创建了一个新的凭证文件 https://www.hardworkingnerd.com/how-to-read-and-write-to-google-sheets-with-c/ (感谢您的精彩分享,伊恩)
但即使使用新的凭据文件,我也遇到了同样的错误。
这是我的代码:
var credential = GoogleCredential.FromStream(new FileStream(credentialFileName, FileMode.Open)).CreateScoped(Scopes);
_sheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
...
SpreadsheetsResource.ValuesResource.GetRequest request =
_sheetsService.Spreadsheets.Values.Get(_spreadsheetId, range);
var response = request.Execute(); // Here, I got the error.
如果我使用基于 OAuth 的凭据(抱歉,我不知道它的确切术语),例如 https://developers.google.com/sheets/api/quickstart/dotnet,那么它可以正常工作。
这是我使用基于 OAuth 的凭据的代码。
UserCredential credential;
using (var stream = new FileStream(credentialFileName, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
_sheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
...
// Rest codes are same
半天来我一直在为这个错误而苦苦挣扎。
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
您仍然可以访问旧机器吗?您可以发布您的旧凭据文件吗?您在每台机器上使用什么版本的 .net - 与版本有关吗?还是dotnetframework vs dotnetcore?您还建议在您以前的机器上没有使用 OAuth - 您确定吗?您最后一次使用您的应用是什么时候?
标签: c# .net google-sheets-api