2

我正在使用带有 key.p12 证书的服务帐户来访问谷歌日历 API。但是,它无法访问域中任何用户的日历。我确实按照将域范围的权限委派给服务帐户的步骤 https://developers.google.com/accounts/docs/OAuth2ServiceAccount

它没有 .net 的代码示例。看来我只能在 google .net 客户端库中获得 ServiceAccountCredential 。这是我的代码

    static void Main(string[] args)
    {
        string serviceAccountEmail = "xxxx@developer.gserviceaccount.com";
        var certificate = new X509Certificate2(@"clientPrivateKey.p12", "notasecret",  X509KeyStorageFlags.Exportable);

        Console.WriteLine("service account: {0}", serviceAccountEmail);

        ServiceAccountCredential credential = new ServiceAccountCredential(new
        ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new[] { CalendarService.Scope.Calendar }
        }.FromCertificate(certificate));

        BaseClientService.Initializer initializer = new  BaseClientService.Initializer();            

        initializer.HttpClientInitializer = credential;           
        initializer.ApplicationName = "Google Calendar Sample";
        CalendarService calservice = new CalendarService(initializer);

        // list all the calendars it can see
        try
        {
            var list = calservice.CalendarList.List().Execute();

            if (list.Items.Count > 0)
            {
                foreach(var item in list.Items)
                {
                    Console.WriteLine("Found calendar for account {0}", item.Id);
                }
            }
            else
            {
                Console.WriteLine("Calendar list for this service account is empty");
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

日历列表始终为空。如果我在日历设置中手动与此服务帐户共享我的域帐户日历,则此代码会成功返回我的域帐户日历。

有没有办法让这个服务帐户访问域中所有用户的日历?

4

2 回答 2

2

实际上,代码应该使用服务帐户来“冒充”域用户,而不是尝试与服务帐户共享日历。

    ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new[] { CalendarService.Scope.Calendar },
        User = "myaccount@mydomain.com" // impersonate domain user
    }.FromCertificate(certificate));

还需要按照在谷歌域管理控制台中将域范围的权限委托给服务帐户的步骤,并添加正确的范围(对于日历,它是https://www.googleapis.com/auth/calendar

于 2014-12-10T07:56:58.687 回答
0

正如您所指出的,您需要与服务帐户共享现有日历

<paste-your-account-here>@developer.gserviceaccount.com

(您可以在 Google Developers Console 的凭据选项卡下找到相关帐户,它称为“电子邮件地址”)

希望能帮助到你。

于 2014-12-08T17:46:05.360 回答