[英]Add event to Google Calendar via API v3 using OAuth 2.0 service account?
[英]Error accessing Google Calendar using OAuth2.0. and service account: “Invalid impersonation prn email address.”
我正在嘗試使用OAuth2.0和服務帳戶使用Google Calendar API訪問組織日歷中各種用戶的日歷,但出現錯誤
“” invalid_request“”無效的模擬PRN電子郵件地址。“。
在Google控制台中,我有:
-創建了一個項目
-創建了一個服務帳戶並啟用了“域范圍委托”,並賦予了“項目所有者”角色,然后獲得了P12密鑰。
-在“安全性”>“高級設置”>“身份驗證”>“管理API客戶端訪問”中,我已授予服務帳戶訪問https://www.googleapis.com/auth/calendar.readonly的權限。
using System;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
namespace Google_Calendar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string GoogleCertificate = @"testcalendar-209521-772939e76cae.p12"; // keyfile filename
string GoogleEmail = @"myserviceaccount@testcalendar-209521.iam.gserviceaccount.com"; // serviceaccount mail
string GoogleUser = "MyServiceAccount"; // serviceaccount name
string[] Scopes = new string[] { "https://www.googleapis.com/auth/calendar.readonly" };
X509Certificate2 certificate = new X509Certificate2(GoogleCertificate, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(GoogleEmail)
{
Scopes = Scopes,
User = GoogleUser
}.FromCertificate(certificate));
CalendarService service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "testcalendar" });
string CalenderID = "mathias@mydomain.com";
var CalRequest = service.Events.List(CalenderID);
CalRequest.TimeMin = DateTime.Now.AddMonths(-1); //optional parameter
CalRequest.TimeMax = DateTime.Now.AddMonths(+1); //optional parameter
do
{
var events = CalRequest.Execute(); // here I get the error
foreach (var item in events.Items)
{
// do stuff
}
CalRequest.PageToken = events.NextPageToken;
} while (CalRequest.PageToken != null);
}
}
}
任何想法可能是什么問題? 我認為問題出在我在Google某處的設置中。 我會錯過一步嗎?
在Google支持的一些幫助下,我解決了該問題。
1:使用服務帳戶用戶的位置
string GoogleUser = "MyServiceAccount";
我應該使用模擬用戶
string GoogleUser = "MyAdminUser";
2:當我在管理控制台上添加范圍時,我通過使用“服務帳戶”電子郵件進行了添加,然后將其可視化地轉換為項目的ClientID,並且一切正常。 但事實並非如此。 當我改用ClientID時,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.