【问题标题】:How do I create a GoogleCredential from an authorized access_token?如何从授权的 access_token 创建 GoogleCredential?
【发布时间】:2017-06-02 20:41:55
【问题描述】:

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

【问题讨论】:

  • 我不熟悉 C#,但我认为OAuth 2.0 in C# 的指南将帮助您创建具有授权 access_token 的 driveService。这还将提供区分用户凭据和 ServiceAccountCredential 的指南。希望这会有所帮助。
  • 我正试图做相反的事情。我有一个GoogleCredential,我需要获得一个访问令牌。有什么想法吗?

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


【解决方案1】:

我已经设法弄清楚了。

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

【讨论】:

  • 您在控制台中创建了哪种类型的应用程序?是网络还是其他?因为 Android 或 Ios 没有客户端密码。你是用 xamairn auth 来获取令牌的吗?
猜你喜欢
  • 2017-05-19
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多