26

I am using "Google.Apis.Bigquery.v2 Client Library" with C#.

I am authorizing to Google BigQuery using "Service Account" (see http://www.afterlogic.com/mailbee-net/docs/OAuth2GoogleServiceAccounts.html). To create the X509 certificate I use the p12 key from the Google Developers Console. However, right now the json key is the default. Can I use it instead the p12 key?

I have the following code:

    string serviceAccountEmail = "xxxx@developer.gserviceaccount.com";

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();
Andrey Belykh
  • 2,234
  • 3
  • 28
  • 42
  • Similar (unanswered) question is here http://stackoverflow.com/questions/30884184 – Andrey Belykh Aug 11 '15 at 20:18
  • Have you tried using this flow: http://stackoverflow.com/questions/19977864/nativeapplicationclient-is-not-supported-any but for BQ? – Ryan Aug 14 '15 at 18:21
  • This is actually very close. Do you have a similar example for ServiceAccountCredential (not UserCredential)? – Andrey Belykh Aug 17 '15 at 14:00
  • 1
    Looking at the source code I don't think its possible. Reading the example project they use ServiceAccountCredentials for all except with Json. https://github.com/google/google-api-dotnet-client/blob/9405c89aff6cc7454619a5af560f3b7efbc3f4f6/Src/GoogleApis.Auth.DotNet4/OAuth2/ServiceAccountCredential.cs https://cloud.google.com/storage/docs/json_api/v1/json-api-dotnet-samples – Ryan Aug 17 '15 at 16:41

3 Answers3

16

It is now possible (I used v 1.13.1.0 of Google APIs).

Example for 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);

Example for Google Sheets:

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;
Andrey Belykh
  • 2,234
  • 3
  • 28
  • 42
4

I got the link, Which indicates Service Account Authentication using JSON file in C# application is not yet added in Google BigQuery API.

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

selva kumar
  • 966
  • 2
  • 8
  • 25
3

This is working for me:

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;
}

Obviously, you would provide your own values for the scopes variable and for the path to the key file. You would also need to get the Google.Apis.Auth.OAuth2 Nuget package plus whatever other service-specific package you plan on using the credential with (in my case it is Google.Apis.Drive.v3).

July.Tech
  • 1,166
  • 13
  • 17