Search code examples
google-calendar-api.net-6.0

Google CalendarService throws Request had invalid authentication credentials


I have a problem with the authentication to the .NET client API for calling the Google Calendar API since I made a change on how I initialize the service.

So basically I first had this (which worked) :

private static async Task<CalendarService> CreateCalendarServiceAsync()
{
    GoogleCredential credential;

    await using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
    {
        credential = GoogleCredential.FromStream(stream)
            .CreateScoped(CalendarService.Scope.Calendar);
    }

    return new CalendarService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential
    });
}

But then I changed to the following to be able to store the credentials in my configuration so that the production credentials will never be in the source code, but only in the Azure App Service configuration. Note that the credentials is the JSON file I got from cloud console for a service account.

private CalendarService CreateCalendarServiceAsync()
{
    return new CalendarService(new BaseClientService.Initializer
    {
        HttpClientInitializer = GoogleCredential.FromJson(this._applicationSettings.ServiceAccountCredentials)
    });
}

The credentials itself is exactly the same, as I just copy pasted it into my appsettings.Dev.json. And from there I get this error whenever I am calling the API : The service calendar has thrown an exception. HttpStatusCode is Unauthorized. Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

I looked up a bit about it, but I didn't find a solution to this. Do you have any idea of what is going wrong there ?

Thanks


Solution

  • I forgot to rewrite the scope of the credentials : GoogleCredential.FromJson(myJson).CreateScoped(CalendarService.Scope.Calendar)

    Adding the scope fixed my issue