Skip to content

Instantly share code, notes, and snippets.

@tjmoore
Created August 11, 2015 12:11
Show Gist options
  • Select an option

  • Save tjmoore/6947d152eb5cfa569ef1 to your computer and use it in GitHub Desktop.

Select an option

Save tjmoore/6947d152eb5cfa569ef1 to your computer and use it in GitHub Desktop.

Revisions

  1. tjmoore created this gist Aug 11, 2015.
    30 changes: 30 additions & 0 deletions service_account_with_json_key.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    // Simple code snippet showing use of Google Service Account JSON key file within ServiceAccountCredential.

    using System.IO;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Calendar.v3;
    using Google.Apis.Calendar.v3.Data;
    using Google.Apis.Services;
    using Newtonsoft.Json.Linq;

    var serviceAccountJson = File.ReadAllText("<JSON-FILE-HERE>");

    var o = JObject.Parse(serviceAccountJson);

    var email = o["client_email"].ToString();
    var privateKey = o["private_key"].ToString();

    ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(email)
    {
    Scopes = new[] { CalendarService.Scope.CalendarReadonly }
    }.FromPrivateKey(privateKey);

    // Just an example initialising Calendar API
    var service = new CalendarService(new BaseClientService.Initializer
    {
    HttpClientInitializer = credential,
    ApplicationName = "APP-NAME-HERE"
    });

    // Then do what you like with the 'service' instance.