everyone.
I had written a C# project which reads/writes to the google sheet, and it works fine. Recently I had replaced my desktop machine, so moved my program into it. When I started my program, I got the following error.
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
I thought its credential maybe be wrong because of my new machine. So I had created a new credential file by referring to this site https://www.hardworkingnerd.com/how-to-read-and-write-to-google-sheets-with-c/ (Thank you for your good sharing, Ian)
But I got the same error even with the new credential file.
This is my code:
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.
If I use the OAuth-based credentials (I'm sorry, I don't know its exact terminology) such as https://developers.google.com/sheets/api/quickstart/dotnet, then it works fine.
Here is my code using OAuth-based credentials.
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
I have been struggling for this error during a half day.
Any help will be appreciated.
Thank you.
This is usually a time issue...
Make sure the clock on your new machine is synced to the correct time.
User contributions licensed under CC BY-SA 3.0