我正在使用带有key.p12证书的服务帐户来访问Google日历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);
}
}
日历列表始终为空。如果我在日历设置中手动与此服务帐户共享我的域帐户日历,则此代码会成功返回我的域帐户日历。
有没有办法让这个服务帐户访问域中的所有用户日历?
答案 0 :(得分:2)
实际上,代码应该使用服务帐户逐个“模仿”域用户,而不是尝试与服务帐户共享日历。
ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { CalendarService.Scope.Calendar },
User = "myaccount@mydomain.com" // impersonate domain user
}.FromCertificate(certificate));
还需要按照将域范围权限委派给google域管理控制台中的服务帐户的步骤,并添加正确的范围(对于日历,它是https://www.googleapis.com/auth/calendar)
答案 1 :(得分:0)
正如您所指出,您需要与服务帐户共享现有日历
<paste-your-account-here>@developer.gserviceaccount.com
(您可以在Google Developers Console的“凭据”标签下找到相关帐户,该帐户名为“EMAIL ADDRESS&#39;”
希望它有所帮助。