google-api-dotnet-client: Unable to create Service Account from JSON

This is my code:

const string serviceAccountEmail = "...";
string[] scopes = { CalendarService.Scope.CalendarReadonly };
Stream stream = new FileStream(@"C:\...\console-generated-key.json", FileMode.Open, FileAccess.Read, FileShare.Read);
var credential = GoogleCredential.FromStream(stream);
credential.CreateScoped(scopes);
var service = new CalendarService(new BaseClientService.Initializer
{
     HttpClientInitializer = credential,
     ApplicationName = "My Application"
});
var request = service.Events.List("my-calendar@resource.calendar.google.com");
var events = request.Execute();

I get the following JSON back from googleapis.com:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

I’m able to authenticate with a .p12 for the same service account using:

ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
     Scopes = scopes,
}.FromCertificate(certificate));

Related: #533

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 16 (3 by maintainers)

Most upvoted comments

@miguelRedit: Given that this issue is over 7 years old, I think it would be more productive to create a new issue with more details.

@miguelRedit: Again, please create a new issue rather than continuing to add things here. But I strongly suspect you’re not actually loading the JSON file you think you are… because assuming the type here is "service_account" you wouldn’t get that error. In the new issue, please provide a complete example with a sample file - obviously not containing your actual credentials, but with all IDs/keys replaced by “xxx”.

The error message you’re showing would happen if you had a JSON file which didn’t specify type at all. (The empty string before the period at the end is the type…)

@miguelRedit The code for authorization has changed its a lot easer now

var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
.CreateScoped(new[] {CalendarService.Scope.CalendarReadonly});

Just make sure you grab the service account key file thats ends in .json and not the .p12 file.