【发布时间】:2014-07-25 01:05:01
【问题描述】:
我正在尝试使用服务帐户将日历从 Dynamics CRM 软件同步到 Google。 在此期间,我面临缺乏关于 .net 的 google API 的文档,尤其是关于授权的文档。由于使用了过时的库和类,大多数 Google 示例甚至无法编译。
所以我在实习中找到了一些示例并收到错误。 有人可以看看我的样本并告诉我我做错了什么吗?
准备步骤:
- 我在我的私人 Google 帐户中创建了一个项目。
- 在项目开发者控制台中,在 APIS & AUTH -> Credentials 下,我生成了服务帐户。然后点击“生成 P12 密钥”并下载 .p12 文件。
- 在 APIS 和 AUTH -> API 下,打开“日历 API”
然后创建控制台应用程序并设法安装 OAuth 和日历 nuget 包。有:
- Google API 身份验证客户端库,Google.Apis.Auth 1.8.1
- Google API 客户端库,Google.Apis 1.8.1
- Google API 核心客户端库,ID:Google.Apis.Core 1.8.1
- Google.APIs.Calendar.v3 客户端库,Google.Apis.Calendar.V3 1.8.1.860
找到了符合我需要的代码:
using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Calendar.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
namespace CrmToGoogleCalendar
{
class Program
{
static void Connect()
{
var certificate = new X509Certificate2("My Project-ee7facaa2bb1.p12", "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountEmail = "506310960175-q2k8hjl141bml57ikufinsh6n8qiu93b@developer.gserviceaccount.com";
var userAccountEmail = "<my email>@gmail.com";
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userAccountEmail,
Scopes = new[] { CalendarService.Scope.Calendar }
}
.FromCertificate(certificate));
var service = new CalendarService(new BaseClientService.Initializer()
{
ApplicationName = "Test calendar sync app",
HttpClientInitializer = credential
});
var calList = service.CalendarList.List().Execute().Items;
foreach (var cal in calList)
{
Console.WriteLine(cal.Id);
}
}
static void Main(string[] args)
{
Connect();
}
}
}
我在应用程序和 Fiddler 中看到的与 Google API 的通信是:
请求:
主机:HTTPS accounts.google.com,网址:/o/oauth2/token
断言:长二进制字符串
grant_type: urn:ietf:params:oauth:grant-type:jwt-bearer
回复:
HTTP/1.1 400 错误请求内容类型:application/json 缓存控制: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache 到期时间:格林威治标准时间 1990 年 1 月 1 日星期五 00:00:00 日期:2014 年 7 月 24 日星期四 06:12:18 GMT X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN X-XSS-防护:1;模式=块服务器:GSE 备用协议: 443:quic 传输编码:分块
1f { "error" : "invalid_grant" } 0
请提前帮助和感谢!
【问题讨论】:
-
嗨@luc。我发现,在谷歌应用程序网页中打开日历后,它开始以
Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""响应。所以同样的代码出现另一个错误。我仍然认为我在正确配置 google 时遗漏了一些东西 -
我在生产服务器上收到此错误。在搜索了这样的答案后,我终于发现这是由于系统时钟关闭所致。 stackoverflow.com/questions/11973162/…
标签: oauth google-api google-calendar-api google-oauth google-api-dotnet-client