如何从授权 access_token 创建 GoogleCredential?

How do I create a GoogleCredential from an authorized access_token?

我有一个这样的 OAuth2 令牌...

{{
  "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in": "3600",
  "refresh_token": "xxxxxxxxxxxxxxxxxx",
  "token_type": "Bearer",
}}

我正在尝试创建一个 DriveService 对象...

Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "foo",
});

(像这样?)

但我显然没有正确执行此操作,而且我在查找文档时遇到了麻烦。

当我尝试创建一个 GoogleCredential 传递给 DriveService

GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);

我得到以下异常:

{System.InvalidOperationException:从 JSON 创建凭据时出错。无法识别的凭据类型。

我是不是完全用错了方法?

(这是the sample code context

我已经弄明白了。

解决方案是用我的 ClientID 和 ClientSecret 创建一个 Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow...

Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow googleAuthFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
  ClientSecrets = new ClientSecrets()
  {
    ClientId = ClientID,
    ClientSecret = ClientSecret,
  }
});

还有一个Google.Apis.Auth.OAuth2.Responses.TokenResponse:

Google.Apis.Auth.OAuth2.Responses.TokenResponse responseToken = new TokenResponse()
{
  AccessToken = SavedAccount.Properties["access_token"],
  ExpiresInSeconds = Convert.ToInt64(SavedAccount.Properties["expires_in"]),
  RefreshToken = SavedAccount.Properties["refresh_token"],
  Scope = GoogleDriveScope,
  TokenType = SavedAccount.Properties["token_type"],
};

并使用每个来创建一个 UserCredential,也就是用于初始化 DriveService...

var credential = new UserCredential(googleAuthFlow, "", responseToken);

Service = new DriveService(new BaseClientService.Initializer()
{
  HttpClientInitializer = credential,
  ApplicationName = "com.companyname.testxamauthgoogledrive",
});

我更新了 TestXamAuthGoogleDrive test harness project 以反映这些变化。