如何使用 .net 中的服务帐户访问域用户的日历? [英] How to access domain users' calendar using service account in .net?
问题描述
我使用带有 key.p12 证书的服务帐户来访问谷歌日历 API.但是,它无法访问域中任何用户的日历.我确实按照将域范围的权限委派给服务帐户的步骤操作https://developers.google.com/accounts/docs/OAuth2ServiceAccount
I am using service account with key.p12 cert to access google calendar API. However, it cannot access any user's calendar in the domain. I did follow the steps to Delegating domain-wide authority to the service account https://developers.google.com/accounts/docs/OAuth2ServiceAccount
它没有 .net 的代码示例.看来我只能在 google .net 客户端库中获得 ServiceAccountCredential.这是我的代码
It does not have code sample for .net. And it seems I only get ServiceAccountCredential in the google .net client library. Here is my code
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);
}
}
日历列表总是空的.如果我在日历设置中手动与此服务帐户共享我的域帐户日历,则此代码会成功返回我的域帐户日历.
The calendar list is always empty. If I manually share my domain account calendar with this service account in the calendar setting, then this code returns my domain account calendar successfully.
有没有办法让这个服务帐户访问域中所有用户的日历?
Is there a way to make this service account access all the user's calendar in the domain?
推荐答案
实际上,代码应该使用服务帐户来模拟"域用户,而不是尝试与服务帐户共享日历.
Actually, the code should use service account to "impersonate" the domain users one by one, rather than trying to share calendars with service account.
ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { CalendarService.Scope.Calendar },
User = "myaccount@mydomain.com" // impersonate domain user
}.FromCertificate(certificate));
还需要按照在google域管理控制台中将域范围的权限委派给服务帐户的步骤操作,并添加正确的范围(对于日历,它是https://www.googleapis.com/auth/calendar )
Also need follow the steps for Delegating domain-wide authority to the service account in google domain admin console, and add the right scope( for calendar, it is https://www.googleapis.com/auth/calendar )
这篇关于如何使用 .net 中的服务帐户访问域用户的日历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!