如何通过授权的access_token创建GoogleCredential?

dan*_*anb 3 drive oauth-2.0 google-drive-api

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

{{
  "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in": "3600",
  "refresh_token": "xxxxxxxxxxxxxxxxxx",
  "token_type": "Bearer",
}}
Run Code Online (Sandbox Code Playgroud)

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

Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "foo",
});
Run Code Online (Sandbox Code Playgroud)

(像这样?)

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

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

GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

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

我会完全以错误的方式解决这个问题吗?

(这是示例代码上下文

dan*_*anb 5

我设法弄清楚了。

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

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

还有一个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"],
};
Run Code Online (Sandbox Code Playgroud)

并使用每个参数创建一个UserCredential,依次用于初始化DriveService ...

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

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

我更新了TestXamAuthGoogleDrive测试工具项目以反映这些更改。