Подтвердить что ты не робот

Можно ли использовать ключ json вместо ключа p12 для учетных данных учетной записи службы?

Я использую "Клиентскую библиотеку Google.Apis.Bigquery.v2" с С#.

Я разрешаю Google BigQuery использовать "Учетную запись службы" (см. http://www.afterlogic.com/mailbee-net/docs/OAuth2GoogleServiceAccounts.html). Чтобы создать сертификат X509, я использую ключ p12 из Google Developers Console. Тем не менее, сейчас json-ключ является значением по умолчанию. Могу ли я использовать его вместо ключа p12?

У меня есть следующий код:

    string serviceAccountEmail = "[email protected]";

X509Certificate2 certificate;
using (Stream stream = new FileStream(@"C:\key.p12", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    using (MemoryStream ms = new MemoryStream())
    {
        stream.CopyTo(ms);
        certificate = new X509Certificate2(ms.ToArray(), "notasecret", X509KeyStorageFlags.Exportable);
    }
}

// Create credentials
ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new[] {
        BigqueryService.Scope.Bigquery,
        BigqueryService.Scope.CloudPlatform,
    },
    }.FromCertificate(certificate));

// Create the service
BaseClientService.Initializer initializer = new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "My Application",
    GZipEnabled = true,
};

BigqueryService service = new BigqueryService(initializer);
var projects = service.Projects.List().Execute();
4b9b3361

Ответ 1

Теперь это возможно (я использовал v 1.13.1.0 API Google).

Пример для BigQuery:

GoogleCredential credential;
using (Stream stream = new FileStream(@"C:\mykey.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    credential = GoogleCredential.FromStream(stream);
}

string[] scopes = new string[] {
    BigqueryService.Scope.Bigquery,
    BigqueryService.Scope.CloudPlatform, 
};
credential = credential.CreateScoped(scopes);

BaseClientService.Initializer initializer = new BaseClientService.Initializer()
{
    HttpClientInitializer = (IConfigurableHttpClientInitializer)credential,
    ApplicationName = "My Application",
    GZipEnabled = true,
};
BigqueryService service = new BigqueryService(initializer);

Пример для Google Таблиц:

GoogleCredential credential;
using (Stream stream = new FileStream(@"mykey.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    credential = GoogleCredential.FromStream(stream);
}
credential = credential.CreateScoped(new[] { 
    "https://spreadsheets.google.com/feeds", 
    "https://docs.google.com/feeds" });

string bearer;
try
{
    Task<string> task = ((ITokenAccess)credential).GetAccessTokenForRequestAsync();
    task.Wait();
    bearer = task.Result;
}
catch (AggregateException ex)
{
    throw ex.InnerException;
}

GDataRequestFactory requestFactory = new GDataRequestFactory("My Application");
requestFactory.CustomHeaders.Add(string.Format(CultureInfo.InvariantCulture, "Authorization: Bearer {0}", bearer));

SpreadsheetsService service = new SpreadsheetsService("My Application");
service.RequestFactory = requestFactory;

Ответ 2

Я получил ссылку, которая указывает, что Аутентификация учетной записи службы с использованием файла JSON в приложении С# еще не добавлена ​​в Google BigQuery API.

https://github.com/google/google-api-dotnet-client/issues/533

Ответ 3

Это работает для меня:

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

ServiceAccountCredential credential;
using (Stream stream = new FileStream(@"C:\path\key.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    credential =
        GoogleCredential.FromStream(stream).CreateScoped(scopes).UnderlyingCredential as
            ServiceAccountCredential;
}

Очевидно, вы предоставили бы свои собственные значения для переменной scopes и для пути к ключевому файлу. Вам также понадобится получить пакет Google.Apis.Auth.OAuth2 Nuget плюс любой другой пакет услуг, на котором вы планируете использовать учетные данные (в моем случае это Google.Apis.Drive.v3).