加载服务帐户Json密钥文件

时间:2016-03-11 08:27:27

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

Google最近开始向我们提供服务帐户的Json密钥文件,而不是P12密钥文件。我一直试图得到这个,那里没有很多信息,我看到的信息说这应该有效。

string[] scopes = new string[] { DriveService.Scope.Drive}; 

Stream stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var credential = GoogleCredential.FromStream(stream).CreateScoped(scopes); 

然而它抛出以下异常

  

从JSON创建凭据时出错。无法识别的凭据类型。

我已经仔细检查了json密钥文件,下载了两个不同的文件,试图让它无法正常工作。

4 个答案:

答案 0 :(得分:1)

我下载了一个服务帐户json密钥文件,并尝试了相同的代码,它工作正常。如果我手动损坏"类型"我能够复制该问题。 json密钥文件中的字段。你可以重新下载一个json密钥文件,然后再试一次。以下是json密钥文件的外观(删除了敏感数据):

{
  "type": "service_account",
  "project_id": ...,
  "private_key_id": ...,
  "private_key": ...,
  "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": ...
}

答案 1 :(得分:1)

我认为您正在使用从Firebase下载的文件google-services.json。这不是您需要的文件。您要做的过程是:

  1. 转到 Firebase控制台
  2. 点击设置
  3. 点击项目设置
  4. 点击服务帐户
  5. 点击生成新私钥按钮
  6. 使用通过此方法生成的文件。

答案 2 :(得分:0)

以下代码用于通过旧json文件或.p12文件进行身份验证。

public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Calendar service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountCalendarFailed", ex);
            }
        }
    }
}

ServiceAccount.cs翻录的代码

答案 3 :(得分:-1)

我认为您首先需要对流进行反序列化,至少是我在https://github.com/google/google-api-dotnet-client/blob/a5288c4493a12791b46f7142efacb83c4fcacf58/Src/Support/GoogleApis.Auth.PlatformServices_Shared/OAuth2/DefaultCredentialProvider.cs#L169

找到的内容。

试试看,告诉我们。 是的,我们需要改进文档,但让我们首先找到问题,然后我将在GitHub中根据具体请求打开一个新问题。