首页 文章

使用OAuth2.0访问Google日历时出错 . 和服务帐户:“无效的模拟prn电子邮件地址 . ”

提问于
浏览
0

我正在尝试使用Google Calendar API使用OAuth2.0和服务帐户访问组织日历中各种用户的日历,但我收到错误消息

“invalid_request”“模仿电子邮件地址无效 . ” .

在Google控制台中,我有:

  • 创建了一个项目
  • 创建了一个服务帐户并启用了"Domain wide delegation"并赋予了"Project Owner"角色,然后获得了一个P12密钥 .
  • 在安全性>高级设置>身份验证>管理API客户端访问中,我已授予对https://www.googleapis.com/auth/calendar.readonly的serviceaccount访问权限 .
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设置中 . 我错过了一步吗?

1 回答

  • 0

    在Google支持的帮助下,我解决了这个问题 .

    1:我使用过服务帐户的用户
    string GoogleUser = "MyServiceAccount";
    我应该使用模仿用户
    string GoogleUser = "MyAdminUser";

    2:当我在管理控制台上添加范围时,我使用服务帐户电子邮件添加了它,然后将其直观地翻译为我的项目的ClientID,一切似乎都没问题 . 但事实并非如此 . 当我改为使用ClientID时,一切正常 .

相关问题