如何从授权的access_token创建GoogleCredential?

时间:2017-06-02 20:41:56

标签: oauth-2.0 google-drive-api drive

我有这样的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

1 个答案:

答案 0 :(得分:2)

我已经设法解决了这个问题。

解决方案是使用我的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以反映这些变化。