Created
August 11, 2015 12:11
-
-
Save tjmoore/6947d152eb5cfa569ef1 to your computer and use it in GitHub Desktop.
Simple code snippet showing use of Google Service Account JSON key file within ServiceAccountCredential
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
my code as the following very similar to above and I am getting the System.Exception - Inner Exception/Format Exception: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.DataTransfer.datatransfer_v1;
using System.Collections.Generic;
using Google.Apis.Admin.DataTransfer.datatransfer_v1.Data;
public class ServiceAccountJson
{
public string type { get; set; }
public string project_id { get; set; }
public string private_key_id { get; set; }
public string private_key { get; set; }
public string client_email { get; set; }
public string client_id { get; set; }
public string auth_uri { get; set; }
public string token_uri { get; set; }
public string auth_provider_x509_cert_url { get; set; }
public string client_x509_cert_url { get; set; }
am I missing some thing ? Please help. Many thanks in advance.