使用刷新令牌进行 C#sharp 身份验证的 Google.Apis 客户端

eCo*_*rke 3 c# google-api oauth-2.0 google-api-dotnet-client

我正在使用适用于 .NET 的新测试版 Google API 客户端库来加载多个用户的任务列表。它被归类为“已安装的应用程序”(根据谷歌开发控制台),具有多个授权用户帐户。验证一个用户的身份非常简单(使用 google.apis),但我不知道如何使用刷新令牌执行相同的操作,以及如何使用此令牌来获取服务对象。

示例代码:

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(GoogleTools.GenerateStreamFromString(GoogleTools.Cred)).Secrets,
new[] { TasksService.Scope.Tasks },
"user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;         


// Create the service.
service = new TasksService(new BaseClientService.Initializer()
{
     HttpClientInitializer = credential,
     ApplicationName = "Tasks API Sample",
});
Run Code Online (Sandbox Code Playgroud)

我想credential使用刷新令牌构造对象,但我真的迷失了,找不到任何合适的文档。

mqu*_*eia 7

您可以使用以下代码检查当前Token是否过期并刷新:

if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
{
  var refreshResult = credential.RefreshTokenAsync(CancellationToken.None).Result;
}
Run Code Online (Sandbox Code Playgroud)

之后凭证已credential.Token.AccessToken刷新credential.Token.RefreshToken

  • `GoogleCredential.FromAccessToken` 没有 `RefreshTokenAsync` (3认同)