【问题标题】:Google Drive API v3 use JSON instead of P12 (Service Account) - Unexpected characterGoogle Drive API v3 使用 JSON 而不是 P12(服务帐户) - 意外字符
【发布时间】:2016-06-15 03:00:14
【问题描述】:

错误:解析值时遇到意外字符:e。小路 '',第 0 行,第 0 位。

我正在使用 Google .Net 客户端库来访问 Google 驱动器 API v3,特别是 Google.Apis.Drive.v3 包。我正在通过 C# 授权使用“服务帐户”。

p12 密钥授权没问题。但是,建议使用 JSON,并保留 p12 格式以实现向后兼容性。

我从 Google Developers Console 下载了 JSON 文件并尝试使用以下代码进行授权:

    public static Google.Apis.Drive.v3.DriveService AuthenticateServiceAccountJSON(string keyFilePath) {

        // check the file exists
        if (!File.Exists(keyFilePath)) {
            Console.WriteLine("An Error occurred - Key file does not exist");
            return null;
        }

        string[] scopes = new string[] { DriveService.Scope.Drive,                  // view and manage your files and documents
                                         DriveService.Scope.DriveAppdata,           // view and manage its own configuration data
                                         DriveService.Scope.DriveFile,              // view and manage files created by this app
                                         DriveService.Scope.DriveMetadataReadonly,  // view metadata for files
                                         DriveService.Scope.DriveReadonly,          // view files and documents on your drive
                                         DriveService.Scope.DriveScripts };         // modify your app scripts     

        try {
            using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read)) {
                var credential = GoogleCredential.FromStream(stream);
                if (credential.IsCreateScopedRequired) {
                    credential.CreateScoped(scopes);
                }
                // Create the service.
                Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() {
                    HttpClientInitializer = credential,
                    ApplicationName = "MyDrive",
                });
                return service;
            }
        } catch (Exception ex) {
            Console.WriteLine(ex.InnerException);
            return null;

        }
    }

我在记事本中查看了 JSON 文件,它似乎是加密的。

“ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAicmFkaWFudC1tZXJjdXJ5LTEyMjkwNyIsCiAgIn....”

可以继续使用P12吗?

【问题讨论】:

标签: c# google-api google-drive-api google-api-dotnet-client service-accounts


【解决方案1】:

这适用于我使用 Google Developers Console 中的 JSON 凭据文件。我正在使用分析服务,但只需为 Drive 服务换出适当的名称:

private AnalyticsReportingService service;

public async Task GetAuthorizationByServiceAccount()
    {
        string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // Put your scopes here
        var keyFilePath = AppContext.BaseDirectory + @"KeyFile.json";

        //Console.WriteLine("Key File: " + keyFilePath);

        var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read);

        var credential = GoogleCredential.FromStream(stream);
        credential = credential.CreateScoped(scopes);

        service = new AnalyticsReportingService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "<Your App Name here>",
        });
    }

【讨论】:

【解决方案2】:

确保您正在下载正确的文件...

GoogleCredential.FromStream(stream)

适用于 JSON 文件。它应该看起来像这样:

{
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "-----BEGIN PRIVATE KEY-----
---END PRIVATE KEY-----\n",
  "client_email": "",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": ""
}

您可以通过单击显示客户端 ID 的网格右侧的“下载 JSON”按钮在 https://console.developers.google.com/apis/credentials 获取此文件。只需确保所选 ID 的类型为“服务帐户客户端”即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2017-08-31
    • 2012-09-30
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多