Search code examples
.netgoogle-apigoogle-calendar-apigoogle-apps

Google API Service Account Initialisation


I am working on a service which should be able to insert calendar Events into user calendars from various Google Apps domains using a service account. Everything works fine, however I came across a small issue while initialising the service using Google API. The initialisation as described in Google APIs looks something like this:

        string[] scopes = new string[] { CalendarService.Scope.Calendar };
        var certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
        try
        { 
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL) 
                {
                    User = user,
                    Scopes = scopes
                }.FromCertificate(certificate));

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

        catch (Exception ex)
        {
            return null;
        }

The problem I am having is that I would like to be able to check if the CalendarService is connected before I actually try to insert any Event. However the provided code snippet does not run any underlying network communication - it just initialise the service. The whole authentication process happens while executing events e.g.: var eventResult = newEventRequest.Execute();

Is there any nice way how to check if the service is actually connected before creating any events (check for HttpRequestException, TokenResponseException, etc.)? The only solution I can think of would be to insert a simple event and then delete it right after or not use the Google API at all.

Thank you in advance.


Solution

  • Try refreshing token beforehand like this:

    if(credential.RequestAccessTokenAsync(CancellationToken.None).Result)
    {
        AuthenticationKey = credential.Token.AccessToken;
    }
    

    This will try to refresh the Access Token essentially providing you the way to check service connectivity.