Google calendar Api v3 and OAuth2 ServiceAccountCredential i



我正在尝试使用服务帐户凭据连接到Googels API。我已经在Google开发人员控制台中创建了一个服务帐户,我还完成了Google Apps域帐户中的所有设置,但它不起作用。当我尝试在我的谷歌日历中获取事件时,我只收到以下消息。Google.Apis.Auth.OAuth2.Responses.TokenResponseException: 错误:"access_denied" 描述:"请求的客户端未授权"。乌里:"

拜托,我做错了什么?

这是我的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string serviceAccountEmail = ".....@developer.gserviceaccount.com";
        string keyFilePath = @"c:nameName.p12";
        string  userEmail = "name.name@domain.com";
        string[] scopes = new string[] { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarReadonly }; 
        var certificate = new X509Certificate2(keyFilePath, "secret", X--------509rageFlags&???.Exportable);
        var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            User = userEmail,
            Scopes = scopes
        }.FromCertificate(certificate));
        // Create the service.
        var calService = new CalendarService(new BaseClientService.Initializer()
        {
            ApplicationName = "Test calendar",
            HttpClientInitializer = credential,
        });
        string eventid = "_60q30c1g60o0s46chk74oj0dhh64rj8ca16p138dpo74ojedhh8oq34dq4";
        Event myEvent = calService.Events.Get(userEmail, eventid).Execute();
        Literal1.Text = myEvent.Summary;
    }
}

如果您的应用访问用户数据,则需要向您创建的服务帐号授予访问您想要访问的 Google Apps 网域的用户数据的权限。

以下步骤必须由 Google Apps 网域的

管理员执行: 转到 Google 企业应用套件网域的管理控制台。

从控件列表中选择"安全性"。如果未看到"安全性"列出,请从页面底部的灰色栏中选择"更多控件",然后从控件列表中选择"安全性"。

从选项列表中选择高级设置。

在"身份验证"部分中选择"管理第三方 OAuth 客户端访问"。

在"客户端名称"字段中,输入服务帐户的客户端 ID。

在"一个或多个 API 作用域"字段中,输入应向应用程序授予访问权限的范围列表。例如,如果您需要全网域访问 Google 云端硬盘 API 和 Google 日历 API,请输入:https://www.googleapis.com/auth/drive、https://www.googleapis.com/auth/calendar

单击授权。

另外,请检查是否已在代码中包含应用程序尝试访问的所有范围。

如果您仍然看到问题,请告诉我。

我发现了错误。你是对的SGC。我在我的代码中输入了 CalendarService.Scope.Calendar 和 CalendarService.Scope.CalendarReadonly 的 scops。但是在我们的Google Apps域管理员控制台中,我刚刚输入了对 https://www.googleapis.com/auth/calendar 的访问权限。我还必须补充 https://www.googleapis.com/auth/calendar.readonly。很明显,愚蠢的我。

感谢SGC

最新更新