简体   繁体   中英

Google Calendar API ServiceAccountCredential

I am trying to use Google's Calendar API. I pretty much used the exact code from their .NET Quickstart page. Instead of using the UserCredential object, I would like to use the ServiceAccountCredential object so I can authenticate with my service account. The code works fine when I authenticate with the UserCredential object, but I don't want to rely on my users having a Google account. When I try to authenticate with the ServiceAccountCredential object, I do not get any results from the Calendar. I also do not get any error either, just no results. Below is my method for getting my ServiceAccountCredential. Does anyone know what I am missing?

        private ServiceAccountCredential GetServiceAccountCredential()
    {
        ServiceAccountCredential credential = null;

        string[] scopes = { CalendarService.Scope.Calendar };
        using (var stream = EmbededResourceHelper.ExtractResourceAsStream("<<downloaded json file>>.json"))
        {
            var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(stream);
            if (credentialParameters.Type != "service_account"
                || string.IsNullOrEmpty(credentialParameters.ClientEmail)
                || string.IsNullOrEmpty(credentialParameters.PrivateKey))
                throw new InvalidOperationException("JSON data does not represent a valid service account credential.");
            credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
                {
                    Scopes = scopes,
                }.FromPrivateKey(credentialParameters.PrivateKey)
            );
        }
        return credential;
    }

You'll need to share your personal calendar with your service account. To do so, go to your calendar's settings, and under "Share with specific people", put your service account's email (eg myserviceaccount@myprojectname.iam.gserviceaccount.com)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM