oauth-2.0 - 如何从授权的 access_token 创建 GoogleCredential?

标签 oauth-2.0 google-drive-api drive

我有一个像这样的 OAuth2 token ......

{{
  "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 )

最佳答案

我设法弄明白了这一点。

解决方案是创建一个 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,
  }
});

还有一个 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来反射(reflect)这些变化。

关于oauth-2.0 - 如何从授权的 access_token 创建 GoogleCredential?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337136/

相关文章:

java - 如何通过 google Drive api 获取/更改文件敏感度级别(标签)?

Google Drive API V3 如何正确转义查询参数?

powershell - Google Drive API - 具有域范围权限的服务帐户可以列出共享驱动器,但不能列出其内容

javascript - 通过脚本设置对 Team drive 文件的权限

php - JWT 计算签名 SHA256withRSA

c# - 如何在 Azure Active Directory 中使用多个 OpenIdConnectAuthenticationOptions

go - Gin Sessions 将状态和代码存储在 URL 中,我想更改它以使我的 URL 更清晰

security - JWT 刷新 token 流程

javascript - 我是否需要提交以下 Google 云端硬盘范围的验证请求才能从选择器下载文件?

Google-Colaboratory - 如何刷新 google-drive?