正在加载服务帐户 Json 密钥文件 [英] Loading Service account Json key file

查看:95
本文介绍了正在加载服务帐户 Json 密钥文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google 最近开始为我们提供服务帐户的 Json 密钥文件,而不是 P12 密钥文件.我一直在努力解决这个问题,但没有太多信息,我所看到的信息表明这应该有效.

Google has recently started to give us a Json key file for service account instead of the P12 key file. I have been trying to get this there isn't a lot of information out there and what info I have seen says this should work.

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 创建凭据时出错.无法识别的凭据类型.

Error creating credential from JSON. Unrecognized credential type .

我已经仔细检查了 json 密钥文件,下载了两个不同的文件,试图让它不起作用.

I have double checked the json key file downloaded two different ones trying to get it to work nothing.

推荐答案

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

The following code is used for authentication with either the old json file or the .p12 file.

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

这篇关于正在加载服务帐户 Json 密钥文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆