上传 Google 联系人 C# 令牌过期

Upload Google Contacts C# token expire

我写了一个代码,它从 google 帐户联系人列表中删除所有联系人并上传新的联系人列表。我正在使用 Outh2 进行身份验证。一切正常,但访问令牌在 1 小时后过期。错误代码是 401。谁能帮我解决这个问题?

这是我的代码:

string clientId = ConfigurationManager.AppSettings["token"];
        string clientSecret = ConfigurationManager.AppSettings["key"]; ;


        string[] scopes = new string[] { "https://www.google.com/m8/feeds/" }; 
        try
        {

            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                         , scopes
                                                                                         , "myaccount@gmail.com"
                                                                                         , CancellationToken.None
                                                                                         , new FileDataStore("test")).Result;

            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken = credential.Token.AccessToken;
            parameters.RefreshToken = credential.Token.RefreshToken;
            parameters.AccessType = "offline";
            UploadContacts(parameters);
        }

谢谢!

我在我的代码中使用了以下 credential.Token.IsExpired 方法。它在下面的项目中工作正常。

    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{ 
   ClientId = Google.ClientId, ClientSecret = Google.ClientSecret },
   scopes,
   settings.GoogleAccount,
   CancellationToken.None).Result;

   // check token is expired
   if (credential.Token.IsExpired(credential.Flow.Clock))
   {
      if (credential.RefreshTokenAsync(CancellationToken.None).Result)
      {
         //The access token is now refreshed. 
      }
      else
      {
         //The access token has expired but we can't refresh it
      }
   }
   else
   {
      //The access token is OK, continue.
   }
}

希望对您有所帮助。

安德烈亚斯

https://www.andreasulbricht.de/cctsync/