我正在使用带有 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);
}
}
日历列表始终为空。如果我在日历设置中手动与此服务帐户共享我的域帐户日历,则此代码会成功返回我的域帐户日历。
有没有办法让这个服务帐户访问域中所有用户的日历?