谷歌日历API和服务帐户或Web应用程序ID V3 .NET认证 [英] Google Calendar API v3 .NET authentication with Service Account or Web Application ID

查看:687
本文介绍了谷歌日历API和服务帐户或Web应用程序ID V3 .NET认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要连接的谷歌日历在我的 .NET 4.5的应用程序(VS 2013项目)。
我想从日历的所有信息,如:事件,日期,备注,名称,客人,等...

I need to connect a Google Calendar on my .NET 4.5 application (VS 2013 project). I want to get all the information from the Calendar, such as: events, dates, notes, names, guests, etc...

我用的是谷歌开发者控制台同时创建 Web应用程序客户端ID 服务帐户,但我得到不同的错误,也没有结果。
我实现了2个不同的方法,一种使用Web应用程序客户端ID登录,一个使用服务帐户。

I used the Google Developer Console to create both a Web Application Client ID and a Service Account, but I get different errors and no results. I've implemented 2 different methods, one to login with Web Application Client ID and one to use Service Account.

这是常见的ASPX页面

public partial class Calendar : System.Web.UI.Page
{
    // client_secrets.json path.
    private readonly string GoogleOAuth2JsonPath = ConfigurationManager.AppSettings["GoogleOAuth2JsonPath"];

    // p12 certificate path.
    private readonly string GoogleOAuth2CertificatePath = ConfigurationManager.AppSettings["GoogleOAuth2CertificatePath"];

    // @developer... e-mail address.
    private readonly string GoogleOAuth2EmailAddress = ConfigurationManager.AppSettings["GoogleOAuth2EmailAddress"];

    // certificate password ("notasecret").
    private readonly string GoogleOAuth2PrivateKey = ConfigurationManager.AppSettings["GoogleOAuth2PrivateKey"];

    // my Google account e-mail address.
    private readonly string GoogleAccount = ConfigurationManager.AppSettings["GoogleAccount"]; 

    protected void Page_Load(object sender, EventArgs e)
    {
        // Enabled one at a time to test
        //GoogleLoginWithServiceAccount();
        GoogleLoginWithWebApplicationClientId();
    }
}

使用Web应用程序客户端ID

我试图以配置JSON配置文件重定向的URI参数,但没有URI似乎工作。我在开发环境,所以我使用端口44300 IIS防爆preSS(启用SSL)。我得到的错误是:

I've tried to configure the redirect URIs parameter for the JSON config file, but no URI seems to work. I'm on development environment so I'm using IIS Express on port 44300 (SSL enabled). The error I'm getting is:

Error: redirect_uri_mismatch
Application: CalendarTest
The redirect URI in the request: http://localhost:56549/authorize/ did not match a registered redirect URI.
Request details
scope=https://www.googleapis.com/auth/calendar
response_type=code
redirect_uri=http://localhost:56549/authorize/
access_type=offline
client_id=....apps.googleusercontent

的code

private void GoogleLoginWithWebApplicationClientId()
{
    UserCredential credential;

    // This example uses the client_secrets.json file for authorization.
    // This file can be downloaded from the Google Developers Console
    // project.
    using (FileStream json = new FileStream(Server.MapPath(GoogleOAuth2JsonPath), FileMode.Open,
        FileAccess.Read))
    {
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(json).Secrets,
            new[] { CalendarService.Scope.Calendar },
            "...@developer.gserviceaccount.com", CancellationToken.None,
            new FileDataStore("Calendar.Auth.Store")).Result;
    }

    // Create the service.
    CalendarService service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "CalendarTest"
    });

    try
    {
        CalendarListResource.ListRequest listRequest = service.CalendarList.List();
        IList<CalendarListEntry> calendarList = listRequest.Execute().Items;

        foreach (CalendarListEntry entry in calendarList)
        {
            txtCalendarList.Text += "[" + entry.Summary + ". Location: " + entry.Location + ", TimeZone: " +
                                    entry.TimeZone + "] ";
        }
    }
    catch (TokenResponseException tre)
    {
        txtCalendarList.Text = tre.Message;
    }
}

使用服务帐户(preferred)

我能达到 CalendarListResource.ListRequest listRequest = service.CalendarList.List(); 行,所以我想在登录的作品,但后来,当我想名单在的IList&LT; CalendarListEntry&GT; calendarList = listRequest.Execute()项目; 我收到以下错误:

I can reach the CalendarListResource.ListRequest listRequest = service.CalendarList.List(); line, so I guess the login works, but then, when I want the list on IList<CalendarListEntry> calendarList = listRequest.Execute().Items; I get the following error:

Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""

的code

private void GoogleLoginWithServiceAccount()
{
    /*
     * From https://developers.google.com/console/help/new/?hl=en_US#generatingoauth2:
     * The name of the downloaded private key is the key's thumbprint. When inspecting the key on your computer, or using the key in your application,
     * you need to provide the password "notasecret".
     * Note that while the password for all Google-issued private keys is the same (notasecret), each key is cryptographically unique.
     * GoogleOAuth2PrivateKey = "notasecret".
     */
    X509Certificate2 certificate = new X509Certificate2(Server.MapPath(GoogleOAuth2CertificatePath),
        GoogleOAuth2PrivateKey, X509KeyStorageFlags.Exportable);

    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
        {
            User = GoogleAccount,
            Scopes = new[] { CalendarService.Scope.Calendar }
        }.FromCertificate(certificate));

    // Create the service.
    CalendarService service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "CalendarTest"
    });

    try
    {
        CalendarListResource.ListRequest listRequest = service.CalendarList.List();
        IList<CalendarListEntry> calendarList = listRequest.Execute().Items;

        foreach (CalendarListEntry entry in calendarList)
        {
            txtCalendarList.Text += "[" + entry.Summary + ". Location: " + entry.Location + ", TimeZone: " +
                                    entry.TimeZone + "] ";
        }
    }
    catch (TokenResponseException tre)
    {
        txtCalendarList.Text = tre.Message;
    }
}

我preFER的服务帐户登录,因为没有必要为用户提供同意画面登录,因为应用程序应该由自己每次需要刷新的时间做到这一点。是否有可能使用服务帐户与免费的谷歌帐户,或者我需要管理控制台?我读过关于许多相互矛盾的报道...

I prefer the Service Account login because there's no need for user to login with consent screen, since the application should do it by itself each time it needs to refresh. Is it possible to use a Service Account with free Google Account or do I need Admin console? I've read many conflicting reports about that...

总之,在寻找计算器各地的谷歌和也,我没有找到一个解决方案。我见过,并试图许多问题和解决方案,但没有结果。一些例子:

Anyway, looking around with Google and also in StackOverflow, I didn't find a solution. I've seen and tried many questions and solutions but with no results. Some examples:

  • Keep getting Error: redirect_uri_mismatch using youtube api v3
  • Google Calendar redirect_uri_mismatch
  • Google API Calender v3 Event Insert via Service Account using Asp.Net MVC
  • https://developers.google.com/google-apps/calendar/instantiate
  • https://groups.google.com/forum/#!topic/google-calendar-api/MySzyAXq12Q

请帮帮忙! : - )

Please help! :-)

更新1 - 使用服务帐户(preferred) - 解决

在我的code唯一的问题是:

The only problem in my code was:

ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
    {
        //User = GoogleAccount,
        Scopes = new[] { CalendarService.Scope.Calendar }
    }.FromCertificate(certificate));

有没有必要 用户= Google账户

推荐答案

肯定是有什么问题您的身份验证。这里是我的服务帐户身份验证方法的副本。

There is definitely something wrong with your authentication. Here is a copy of my Service account authentication method.

 /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            string[] scopes = new string[] {
        CalendarService.Scope.Calendar  ,  // Manage your calendars
        CalendarService.Scope.CalendarReadonly    // View your Calendars
            };

            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                // Create the service.
                CalendarService service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }
        }

我有它的教程以及。我的教程<一个href=\"http://www.daimto.com/google-calendar-api-authentication-with-c/#Google_CalendarAPI_Service_Account_Authentication\"相对=nofollow>谷歌与C#中的code以上是直接从我的样本项目<一把扯下日历API认证href=\"https://github.com/LindaLawton/Google-Dotnet-Samples/blob/master/Google-Calendar/Google-Calendar-Api-dotnet/Google-Clndr-Api-dotnet/Google-Clndr-Api-dotnet/Authentication.cs\"在GitHub上相对=nofollow>谷歌-DOTNET样本项目

I have a tutorial on it as well. My tutorial Google Calendar API Authentication with C# The code above was ripped directly from my sample project Google-Dotnet-Samples project on GitHub

注意/ headsup:请记住,一个服务帐户是不是你。它现在有任何日历当你开始你需要创建一个日历,并将其插入的日历列表中,你会得到任何结果回来。你也不会是能够看到这个日历虽然谷歌日历的Web版本,因为你不能登录为服务帐户。为此各地最好的工作是让你的权限的服务帐户授予的日历。

Note/headsup: Remember that a service account isn't you. It does now have any calendars when you start you need to create a calendar and insert it into the calendar list before you are going to get any results back. Also you wont be able to see this calendar though the web version of Google Calendar because you cant log in as a service account. Best work around for this is to have the service account grant you permissions to the calendar.

这篇关于谷歌日历API和服务帐户或Web应用程序ID V3 .NET认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆